Wasteland
Wasteland

Reputation: 5379

Redux toolkit - update a key value in an object

I need some help with modifying my reducer. I'm using Redux Toolkit and in one of the state slices I've got an object with some grouped settings:

initialState: {
    ...
    userSettings: {mode: 2, subscription: false, setting3: 'text', setting4: 'another text'},
    ...
}

a reducer I have is:

setUserSettings: (state, action) => {
    state.userSettings: action.payload
}

In different parts of a component, I'd update individual settings from the userSettings object:

dispatch(setUserSettings({ mode: 4 }))

in another place:

dispatch(setUserSettings({ setting3: 'some other text'})

How would I modify the reducer to be able to do it? Thanks

Upvotes: 3

Views: 9797

Answers (2)

Ali Alkorsani
Ali Alkorsani

Reputation: 1

change your reducer to

setUserSettings: (state, action) => {state.userSettings={...state.userSettings,action.payload}}

what we did here is making a copy of the old state and then combine it with the new value you need to change the new key of the object will override the old one

Upvotes: -1

Lin Du
Lin Du

Reputation: 102257

Since RTK use immer library underly, you can mutate the state by assigning directly. See Mutating and Returning State

import { configureStore, createSlice } from '@reduxjs/toolkit';

const settingsSlice = createSlice({
  name: 'settings',
  initialState: {
    otherSettings: { ok: true },
    userSettings: { mode: 2, subscription: false, setting3: 'text', setting4: 'another text' },
  },
  reducers: {
    setUserSettings: (state, action) => {
      state.userSettings = { ...state.userSettings, ...action.payload };
    },
  },
});
const { setUserSettings } = settingsSlice.actions;

const store = configureStore({ reducer: settingsSlice.reducer });

store.subscribe(() => {
  console.log(store.getState());
});

store.dispatch(setUserSettings({ mode: 4 }));
store.dispatch(setUserSettings({ setting3: 'some other text' }));

Output:

{
  otherSettings: { ok: true },
  userSettings: {
    mode: 4,
    subscription: false,
    setting3: 'text',
    setting4: 'another text'
  }
}
{
  otherSettings: { ok: true },
  userSettings: {
    mode: 4,
    subscription: false,
    setting3: 'some other text',
    setting4: 'another text'
  }
}

Upvotes: 12

Related Questions