Source:  Twitter logo

I wanna update the state and tried few ways to do that, but I can't. First, I got a problem with fetching state, as a result, I got proxy, not a state.

That is fixed by the current() function by the redux toolkit. Next, where I have a problem is mutation main slice state.

Here is a reducer for mutating.

reducers: {
    setUser: (state, payload) => {
      console.log("before", current(state)); //init state
      state.currentUser = {
        ...state.currentUser,
        loggined: true,
      };
      console.log("after", current(state)); // here I have new state but...
      
    },
    clearUser: (state) => {},
  },

As a result, as a second console log, I got to state what I want, when I want to change a page or just want to do something with new data in the state, by useSelector() redux function, as a result, I got old, not changed state.

Why has this happened?

Example of Slice state:

initialState: {
    currentUser: {
      loggined: false,
      isAdmin: false,
      jwt: false,
    },
  },

Thanks!

Reducers of createSlice use immer:

This object will be passed to createReducer, so the reducers may safely "mutate" the state they are given.

So you can either return a new object that is the new state or "mutate" it and not return it, from createReducer

you need to ensure that you either mutate the state argument or return a new state, but not both.

So you can do:

setUser: (state, payload) => {
  //state here is an immer draft, do not use that to copy current state
  console.log("before", current(state)); //init state
  state.currentUser.loggined = true;
  //not returning anyting
},

Not sure how you'd return a new state based on the old one since ...state makes a copy of the immer draft and not of the state. Can't even find examples of doing this unless it's an array.

7 users liked answer #0dislike answer #07
HMR profile pic
HMR

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).