0

Hey everyone probably a simple question, basically I have a button when i click it fires an action and passes down the whole object that I concat to array if its not duplicate but strangely what happens because I save data to local-storage and after I load it from there it does not check for duplicate and duplicates the array item. My reducer code below maybe the error is there?

Searched as much as possible.

const initialState = {
    favourites: []
};

const favourites = (state = initialState, action) => {
const { payload } = action;
switch (action.type) {
    case actionTypes.ADD_FAVOURITES:
    return {
        ...state,
        favourites:
        state.favourites.indexOf(payload) === -1
            ? state.favourites.concat(payload)
            : state.favourites
    };
    default:
    return state;
}
};
user9013856
  • 328
  • 2
  • 10
  • What is `payload`? – Chris Jun 19 '19 at 19:47
  • payload is an object that i pass – user9013856 Jun 19 '19 at 19:48
  • Is that object saved to localStorage and the one you don't want duplicated? – Chris Jun 19 '19 at 19:50
  • so i add that object to my favourites: [] array which holds all the objects that i clicked and is stored in local storage and loaded from there after – user9013856 Jun 19 '19 at 19:52
  • Alright. I don't know the rest of your code, but perhaps you aren't parsing the object from localStorage? localStorage only saves strings. Saving any object to it will only yield `[object Object]`. What value do you get when receiving the value from ls? – Chris Jun 19 '19 at 19:55
  • i store the whole state of redux i get the array of objects back, but it just doesn't match the duplicate after that and adds duplicate objects into array if that makes sense – user9013856 Jun 19 '19 at 19:58
  • not really, sorry. Can you edit your question and add more relevant code / prints of your variables? I need a better picture – Chris Jun 19 '19 at 20:00

1 Answers1

1

The issue here seems to be that state.favourites.indexOf(payload) === -1 is always true. This is because the function Array.prototype.findIndex() does not find identical objects.

You should use an alternate method of checking to see if the payload object is already in the favourites array. For example, you could try something like this:

const favourites = (state = initialState, action) => {
    const { payload } = action;
    switch (action.type) {
        case actionTypes.ADD_FAVOURITES:
            return {
                ...state,
                favourites:
                    JSON.stringify(state.favourites).indexOf(JSON.stringify(payload)) === -1
                        ? state.favourites.concat(payload)
                        : state.favourites
            };
        default:
            return state;
    }
};
Kris Burke
  • 401
  • 5
  • 8