Ahmed Eid
Ahmed Eid

Reputation: 35

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?

Upvotes: 2

Views: 1073

Answers (2)

Luis Paulo Pinto
Luis Paulo Pinto

Reputation: 6036

As @Stark wrote, looks like you if statement isnt right.

Instead of indexOf, you also can check if a value exists inside an array with includes:

if (!state.favouritesMovies.includes(action.favMovie))

you can check more about it here: includes

Upvotes: 2

Stark Jeon
Stark Jeon

Reputation: 1155

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) 

Upvotes: 2

Related Questions