Search code examples
javascriptreactjsecmascript-6reduxreact-redux

prevent duplicate objects being added to state react redux


I have a question regarding preventing duplicates from being added to my redux store.

It should be straight forward but for some reason nothing I try is working.

export const eventReducer = (state = [], action) => {

    switch(action.type) {

        case "ADD_EVENT":

            return [...state, action.event].filter(ev => {
                if(ev.event_id !== action.event.event_id){
                   return ev;
                }
            });


        default:
            return state;

    }

};

The action looks something like the below:

{
   type: "ADD_EVENT",
   event: { event_id: 1, name: "Chelsea v Arsenal" }
}

The issue is that on occasions the API I am working with is sending over identical messages through a websocket, which means that two identical events are getting added to my store.

I have taken many approaches but cannot figure out how to get this to work. I have tried many SO answers,


Solution

  • Why your code is failing?

    Code:

    return [...state, action.event].filter(ev => {
        if(ev.event_id !== action.event.event_id){
           return ev;
        }
    });
    

    Because first you are adding the new element then filtering the same element, by this way it will never add the new value in the reducer state.


    Solution:

    Use #array.findIndex to check whether item already exist in array or not if not then only add the element otherwise return the same state.

    Write it like this:

    case "ADD_EVENT":
    
        let index = state.findIndex(el => el.event_id == action.event.event_id);
    
        if(index == -1)
            return [...state, action.event];
        return state;