Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Object to empty array in redux toolkit

guys how to append an object to an empty array in redux toolkit? I have set a currentTimeOfServices:[] in my slice then I dispatch an action with a payload dispatch(userActions.getCurrentTime({ startTime: startTime, name: item })); In my getCurrenTtime reducer I don't understand how to append this item.

getCurrentTime: (state, action) => {
      state.currentTimeOfServices = [
        ...state.currentTimeOfServices,
        { startTime: action.payload.startTime, name: action.payload.name },
      ];
    }

This is wrong and I know that but I want to know how to add/append an object to this currentTimeOfServices empty array?

like image 357
Akii J Avatar asked May 22 '26 23:05

Akii J


1 Answers

Redux Toolkit uses Immer inside, which lets you "mutate" the existing state with normal JS syntax. So, all you need is:

state.currentTimeOfServices.push(newItem)

What you've got there is valid for a hand-written immutable update, but it's not necessary here.

See the docs for more details:

  • https://redux.js.org/tutorials/fundamentals/part-8-modern-redux#immutable-updates-with-immer
  • https://redux-toolkit.js.org/usage/immer-reducers
like image 172
markerikson Avatar answered May 24 '26 16:05

markerikson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!