Using createSlice with @redux-toolkit
Two apporach get same result:
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.
CreateSlice structure
โโโโexport const userSlice = createSlice({
โโโโ name: 'user',
โโโโ initialState: {
โโโโ settings: {
โโโโ customTopics: {
โโโโ topicsSortType: { id: 1, name: 'ๆดๆนๆฅๆ', order: 'incr' }
โโโโ }
โโโโ },
โโโโ },
โโโโ reducers: {
โโโโ changeTopicsSortType: (state, action) => {
โโโโ // example bellow
โโโโ },
โโโโ }
โโโโ});
โโโโchangeTopicsSortType: (state, action) => {
โโโโ state.settings.customTopics.topicsSortType.id = action.payload.id;
โโโโ state.settings.customTopics.topicsSortType.name = action.payload.name;
โโโโ},
โโโโchangeTopicsSortType: (state, action) => {
โโโโ return {
โโโโ ...state,
โโโโ settings: {
โโโโ customTopics: {
โโโโ topicsSortType: {
โโโโ ...state.settings.customTopics.topicsSortType,
โโโโ id: action.payload.id,
โโโโ name: action.payload.name
โโโโ }
โโโโ }
โโโโ }
โโโโ };
โโโโ},
Reference: