Skip to content Skip to sidebar Skip to footer

Reactjs: After Action Redux Not Re-render

I have a question, regarding updating a status in redux, I have this code that lists me a few elements and works well, now when I delete one of those elements also works, but the l

Solution 1:

You must handle a DELETE action in your reducers, otherwise redux doesn't know that your state has been updated. In other words:

Your Reducer

exportconstlistReducer = (state=[], action)=>{
  switch(action.type){
    case'GET_GROUP_REQUEST':
      return state;
    case'GET_GROUP_FAILURE':
      return state;
    case'GET_GROUP_SUCCESS':
      return [...state, action.payload];
    case'DELETE_GROUP_SUCCESS':
      const idToDelete = action.payload;
      return state.filter((item) => {
          item.id !== idToDelete
      });
    default:
      return state;     
  }
}

Your Action Creator:

exportconstdeleteGroup = (id, callback)=>{  
    returnfunction(dispatch){
        dispatch({type:'DELETE_GROUP_REQUEST'});
        axios.delete('x/v1/user/tour_groups/'+id)
        .then((response)=>{
            dispatch({type:'DELETE_GROUP_SUCCESS', payload: id});
        })
        .catch((response)=>{
            dispatch({type:'DELETE_GROUP_FAILURE'})
        })
    } 
} 

Please note that 'id' in the reducer must match the key of the object in your state array. Hence if the items in your array look like this:

[ {
    user_id:'12',
    profile: {...}
  },
  ...
]

You must make sure to use:

return state.filter((item) => {
    item.user_id !== idToDelete
});

If your items are simply a flat array of strings then I recommend you refactor how your state looks. Also, I am not familiar with passing callbacks into your action creator, but I'm almost certain that is not good practice.

EDIT: based on your code your DELETE_GROUP_SUCCESS case is wrong. *Note: this assumes that you have a combineReducers call.

case'DELETE_GROUP_SUCCESS':    
    const idToDelete = action.payload;
    return state.filter((tourGroup) => {
        tourGroup.tour_group_key !== idToDelete
    });

Post a Comment for "Reactjs: After Action Redux Not Re-render"