Try โ€‚โ€‰HackMD

redux-toolkit update state in slice

Using createSlice with @redux-toolkit

  • As createSlice creates your actions as well as your reducer for you, you don't have to worry about type safety here. Action types can just be provided inline:

Two apporach get same result:

  • Redux Toolkit mutable (redux-toolkit only)
  • Redux immutable (regular way)

Redux immutable vs Redux-toolkit mutable

What Is Immutability?

  • First off, immutable is the opposite of mutable โ€“ and mutable means changeable, modifiableโ€ฆ able to be messed with.
  • So something that is immutable, then, is something that cannot be changed.

Redux immutable

  • Redux requires reducer functions to be pure and treat state values as immutable.

Redux-toolkit mutable

  • Redux Toolkit allows us to write "mutating" logic in reducers.
    It doesn't actually mutate the state because it uses the Immer library, which detects changes to a "draft state" and produces a brand new immutable state based off those changes.

  • Redux Toolkit's createReducer and createSlice automatically use Immer internally to let you write simpler immutable update logic using "mutating" syntax. This helps simplify most reducer implementations.

mutable and immutable example

CreateSlice structure

โ€‹โ€‹โ€‹โ€‹export const userSlice = createSlice({
โ€‹โ€‹โ€‹โ€‹  name: 'user',
โ€‹โ€‹โ€‹โ€‹  initialState: {
โ€‹โ€‹โ€‹โ€‹    settings: {
โ€‹โ€‹โ€‹โ€‹      customTopics: {
โ€‹โ€‹โ€‹โ€‹        topicsSortType: { id: 1, name: 'ๆ›ดๆ”นๆ—ฅๆœŸ', order: 'incr' }
โ€‹โ€‹โ€‹โ€‹      }
โ€‹โ€‹โ€‹โ€‹    },
โ€‹โ€‹โ€‹โ€‹  },
โ€‹โ€‹โ€‹โ€‹  reducers: {

โ€‹โ€‹โ€‹โ€‹    changeTopicsSortType: (state, action) => {
โ€‹โ€‹โ€‹โ€‹        // example bellow
โ€‹โ€‹โ€‹โ€‹    },
โ€‹โ€‹โ€‹โ€‹  }
โ€‹โ€‹โ€‹โ€‹});

Redux Toolkit mutable (redux-toolkit only)

โ€‹โ€‹โ€‹โ€‹changeTopicsSortType: (state, action) => {
โ€‹โ€‹โ€‹โ€‹  state.settings.customTopics.topicsSortType.id = action.payload.id;
โ€‹โ€‹โ€‹โ€‹  state.settings.customTopics.topicsSortType.name = action.payload.name;   
โ€‹โ€‹โ€‹โ€‹},

Redux immutable (regular way)

โ€‹โ€‹โ€‹โ€‹changeTopicsSortType: (state, action) => {    
โ€‹โ€‹โ€‹โ€‹  return {
โ€‹โ€‹โ€‹โ€‹    ...state,
โ€‹โ€‹โ€‹โ€‹    settings: {
โ€‹โ€‹โ€‹โ€‹      customTopics: {
โ€‹โ€‹โ€‹โ€‹        topicsSortType: {
โ€‹โ€‹โ€‹โ€‹          ...state.settings.customTopics.topicsSortType,
โ€‹โ€‹โ€‹โ€‹          id: action.payload.id,
โ€‹โ€‹โ€‹โ€‹          name: action.payload.name
โ€‹โ€‹โ€‹โ€‹        }
โ€‹โ€‹โ€‹โ€‹      }
โ€‹โ€‹โ€‹โ€‹    }
โ€‹โ€‹โ€‹โ€‹  };
โ€‹โ€‹โ€‹โ€‹},

Reference: