L
L
laguna11322018-02-26 19:57:15
JavaScript
laguna1132, 2018-02-26 19:57:15

What is a side effect?

I'm learning React + Redux. Explain that side effects should be in the middleware. Can't figure out what side effects are? Please explain in simple terms. And why should they be used in middleware?
For example, an example of adding a new comment to an article is given. The author says that the comment id should be generated in the middleware. But we could do it in the reducer. Why is that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-02-26
@laguna1132

Sideeffect is something that can affect the "purity" of your function. The reducer is a function. A pure function means that if you give it the same parameters as input, the result will always be the same.
Example: you have a username in localStorage. And you write something like this in your code:

case SET_DISPLAY_NAME: {
  return {
    ...state,
    name: window.localStorage.getItem('name') ? window.localStorage.getItem('name') : action.payload,
  }
}

Therefore, if you give the function input the name Vasya , then it will return Vasya to you only if there is nothing in "sideeffect local_storage". Here you cannot be sure that if you submit Vasya , Vasya will always return to you . According to the example with comments - I don’t think it’s a good example. IDs will be generated by your backend. You add a new comment by sending it to the server, the status "OK" comes from the server and your comment already has an ID.
It happens that you need to generate IDs yourself, then they are perfectly generated in acftionCreator'ax. For example, you are making a notification system, and each notification must have its own id (for example, you don’t need a server here, you don’t send anything there, just a visual part). In this case, I would not generate id through middleware, but would simply do it in "actions".
However, ID generation is the same as with localStorage. You are not sure that by submitting the input: name, comment text and mail - you will get the same result as last time with the same input parameters (the IDs will be different!)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question