Updating State for changed item not displaying on react frontend

Viewed 129

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;
  }
};
1 Answers

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);
Related