3

I am working on my reducer and I am trying to get the case for UPDATE working.

I am just trying to update the list on my react frontend when a certain object ID changes in the state. How can I make it so the item with a certain ID changes on the frontend in this reducer.

I tried this in UPDATE_ANIMALS, but no luck

case 'UPDATE_ANIMALS':     
    return [      
        ...state, item => item.id === action.payload.id ? action.payload : item

];

Below is my entire reducer.

export const ANIMALSReducer = (state = [], action) => {
  switch (action.type) {
    case 'FETCH_ANIMALS':
      return action.payload;
    case 'ADD_ANIMALS': 
      return [...state, action.payload]; 
    case 'DELETE_ANIMALS': 
      return [      
      ...state.filter(item => item.id !== action.payload)
     ]; 
     case 'UPDATE_ANIMALS':     
      return [      
        NOT SURE WHAT TO PUT HERE
       ];
    default:
      return state;
  }
};
john samcock
  • 137
  • 1
  • 8
  • Does this answer your question? [How to update single value inside specific array item in redux](https://stackoverflow.com/questions/35628774/how-to-update-single-value-inside-specific-array-item-in-redux) – Emile Bergeron Aug 04 '21 at 21:52
  • I tried on my end but i am not sure i am doing it right. Just get an error of undefined. – john samcock Aug 04 '21 at 21:58
  • There's probably something else that's incorrect on your end, but without a [mcve], we can only guess! – Emile Bergeron Aug 04 '21 at 22:02

1 Answers1

2

You can achieve that very easily using the map function, basically you're generating a new array and the matching item given your payload will be updated with the payload instead the original:

case 'UPDATE_ANIMALS':  
    return state.map(item => item.id === action.payload.id ? action.payload : item);
jean182
  • 3,213
  • 2
  • 16
  • 27