Home > database >  Async/Await inside reducer in Redux
Async/Await inside reducer in Redux

Time:09-09

const authSlice = createSlice({
  name: "auth",
  initialState: {
    value: {
      fields: initialState,
    },
  },
  reducers: {
    loginUser: async (state, action) => {
      state.value.fields.loading = true;
      await http
        .post("/login", {
          email: state.value.fields.email,
          password: state.value.fields.password,
        })
        .then((response) => {
          console.log(response.data);
        });
    },
  },
});

I'm receiving an error saying A non-serializable value was detected in the state, in the path: auth. Value: When I try to make this loginUser async.When I remove async await from the loginUser it's working.Really appreciate it if somebody could help.

CodePudding user response:

You must never do any async work inside of a Redux reducer!

One of the primary rules of Redux is:

Reducers must always be 100% synchronous and "pure", with no side effects ( https://redux.js.org/style-guide/#reducers-must-not-have-side-effects )

Additionally, all state updates must be done by "dispatching an action" (like store.dispatch({type: "todos/todoAdded", payload: "Buy milk"}) ), and then letting the reducer look at that action to decide what the new state should be.

If you need to do async work, the right answer is usually to put the async logic into a "thunk", and dispatch actions based on the async results.

I'd strongly recommend going through the Redux docs tutorials to learn more about this and how to use Redux:

https://redux.js.org/tutorials/index

  • Related