Redux Toolkit - I can't update Slice state?

爱⌒轻易说出口 提交于 2021-01-29 08:58:33

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/65765280/redux-toolkit-i-cant-update-slice-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!