D
D
DenJel2016-05-17 14:56:45
React
DenJel, 2016-05-17 14:56:45

Side Effects after reducer execution?

Hello, I'm learning Redux. As I understand it, any asynchronous actions and side effects must occur in the middleware. But If let's say you changed the state in the ruduser and you want to immediately save it to the database (well, or some part of it, that's not the point). How to be then? Somehow I don't understand the logic. Why does the reducer close the state change chain? Explain, please. It is possible on the example of localStorage. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zakhar Orlov, 2016-05-17
@DenJel

The reducer does not close the state change chain. From receives an action and returns a new state. In fact, only a reducer can "change" a state.
Saving data to localStorage is also a side effect and should be done in the middleware.
For example with redux-thunk:

const asyncAction = () => {
  return (dispatch, getState) => {
    localStorage.setItem('state', JSON.stringify(getState()))
    return dispatch(someAction())
  }
}

M
Maxim, 2016-06-08
@maxfarseer

As I understand it, any asynchronous actions and side effects must occur in the middleware.

I don't quite agree. In action creators, you can also perform some side-effect with almost impunity (save the token in localStorage, for example, after LOGIN_SUCCESS).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question