learner
learner

Reputation: 4808

Change inside key of a state in redux reducer

I have following reducer:

   const ListingReducer = (state={
    fetched:false
},action) => {
    if ( action.payload )
    {
        console.log("action.token",action.token);
        console.log("action.payload.profiles",action.payload.profiles);
    }
    switch(action.type)
    {
        case 'SET_LISTING_DATA':
            state = {
                ...state,
                [action.token] : action.payload,
                fetched : true
            }
            break;
        case 'APPEND_LISTING_DATA':
            // console.log("Previous state was: "state[action.token]);
            state[action.token]
             = {
                ...state[action.token],
                profiles : [...state[action.token].profiles,...action.payload.profiles],
                fetched : true
            }
            // console.log("Next state is: "+state[action.token]);

            break;      
    }
    return state;
}

The action:

  1. SET_LISTING_DATA: it sets data into key action.token, which have a key called profiles.
  2. APPEND_LISTING_DATA: it appends data into profile key of state.

I can see the added profiles in profile key, but it doesn't update the view.

The profile is located in:

state[action.token] ={name:y,data:xy,profiles:[id:x,{},{}],...}

Upvotes: 1

Views: 999

Answers (1)

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

It looks like you need to change state[action.token] but also keep previous state data otherwise you will always override your state.

Changing/mutating state props directly is not a good practice though.

case 'APPEND_LISTING_DATA':
  return {
    ...state,
    [action.token]: {
       ...state[action.token],
       profiles: [
         ...state[action.token].profiles,
         ...action.payload.profiles,
       ],
       fetched: true,
    }
  }

Upvotes: 2

Related Questions