3

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?

1 Answer 1

10

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.