1

I want to update Array

initialState

const initialState = { name:'a', arrNames:[1,2,3,4]}

reducer

const userRuducer = createReducer(initialState,(builder)=>{   
    
    builder.addCase('UPDATE_ARRAY',(state,action)=>{
        // how to add ' 12' in the arraay
    })
})

component

 <Button onClick={() =>dispatch({type:'UPDATE_ARRAY',payload:12}) } variant='contained'>update Array</Button>

result:-

arrNames:[1,2,3,4, 12]
asif kaif
  • 159
  • 12

2 Answers2

1

You are using redux-toolkits so it basically just push the new item to the object:

builder.addCase("UPDATE_ARRAY", (state, action) => {
  state.arrNames.push(action.payload)
};

Because redux-toolkits already included with immerjs

Ryan Le
  • 7,708
  • 1
  • 13
  • 23
0
builder.addCase("UPDATE_ARRAY", (state, action) => {
  return {
    ...state,
    arrNames:[...state.arrNames,action.payload]
  };
})

here the state is immutable and conceded as better practice