Search code examples
javascriptreactjsreduxreact-redux

How to add Unique item to array in redux


My movie app has a favourite movies page and you can add movies to your favourite page by clicking on the like button on the movie itself, and I don't want to add the same movie over and over i tried this in my redux reducer:

const initialState = {
 favouriteMovies: []
}

const favMoviesReducer = (state = initialState, action) => {
  
  switch (action.type) { 

    case actionTypes.GET_FAV_MOVIES:

      if (state.favouritesMovies.indexOf(action.favMovie === -1)) {
        return {
          favouritesMovies: [...state.favouritesMovies, action.favMovie],
          // note: action.favMovie is an object 
        };
      }

      return state;

    default:
      return state;
  }
};

but it didn't work so any advice please?


Solution

  • TLDR

    There is some typo in indexOf

    Answer

    Yours code is that

    if (state.favouritesMovies.indexOf(action.favMovie === -1)) 
    

    But, as far as i know, it' right usage of indexOf I guess it is typo.

    if (state.favouritesMovies.indexOf(action.favMovie) === -1)