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;
  }
};
3

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

That is true, I will update the code, thanks
Hmm its not updating on the frontend.
Can you post what does the action.payload is returning?
It started to work! Was just a bug on my side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.