user3348410
user3348410

Reputation: 2833

How assign data to redux initial state array

If I have the initial state in my reducer like that:

let initialState = {
  id: 1,
  url: 'http://',
  name: 'jjj',
  List: []
};

and I want to assign values into this object from different action.types e.g:

List: [
  {
    name: 'a1',
    id: 1
  },
  {
    name: 'a2',
    id: 2
  }
]

here is my reducer:

export default (state = initialState, action) => {
  switch (action.type) {
    case SET_NAME_A:
      return { ...state, List: action.payload };
    case SET_NAME_B:
      return { ...state, List: action.payload };
    default:
      return state;
  }
};

my action.payload giving to me value of input for name a and name b they are different inputs how I can do that?

Upvotes: 0

Views: 880

Answers (2)

Shubham Verma
Shubham Verma

Reputation: 5054

You need to spread reducer so that you just need to update the List :

export default (state = initialState, action) => {
  switch (action.type) {
    case SET_NAME_A:
      return { ...state, List: [...state.List,action.payload ]}; //You can add more conditions base on action
    case SET_NAME_B:
      return { ...state, List: [...state.List,action.payload ] };
    default:
      return state;
  }
};

Upvotes: 0

Panup Pong
Panup Pong

Reputation: 1891

You mean adding element to array in reducer?

return { 
        ...state,
        List: [...state.List, action.payload]
    }

Upvotes: 1

Related Questions