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;
}
};
7
  • What is payload? Commented Jun 19, 2019 at 19:47
  • payload is an object that i pass Commented Jun 19, 2019 at 19:48
  • Is that object saved to localStorage and the one you don't want duplicated? Commented Jun 19, 2019 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 Commented Jun 19, 2019 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? Commented Jun 19, 2019 at 19:55

1 Answer 1

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

Comments

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.