frenchbaguette
frenchbaguette

Reputation: 1339

React item won't remove from array

I have this code here:

const favouriteMovies = (state = initialState, action) => {
  switch(action.type) {
    case 'setMovieToFavourites': return {
      ...state,
      hearted: [...state.hearted, action.movie]
    }
    default: return state;
  }
}

const unlikeMovie = (state = initialState, action) => {
  switch(action.type) {
    case 'unlikeMovie': return {
      ...state,
      hearted: state.hearted.filter(item => item !== action.movie),
    }
    default: return state;
  }
}

So the first function favouriteMovies adds movies to array and with the second function I want to remove the movie from the hearted movies. In the unlikeMovie function I get the movieID which equals to the one of the liked movies but it won't remove the movie from the hearted state. Why it isn't removing ?

Upvotes: 0

Views: 65

Answers (2)

Bmaed Riasbet
Bmaed Riasbet

Reputation: 14998

Can you check this code ?

const movies = (state = initialState, action) => {
  switch(action.type) {
    case 'setMovieToFavourites': return {
      ...state,
      hearted: [...state.hearted, action.movie]
    }

    case 'unlikeMovie': return {
      ...state,
      hearted: state.hearted.filter(item => item !== action.movie),
    }
    default: return state;
  }
}

export default movies;

Upvotes: 1

automasean
automasean

Reputation: 421

Looks like you might need to compare the IDs to filter out the movie in the unlikeMovie function.

Hard to tell for sure without knowing more about the structure of the movie object but assuming action.movie is the same type of object as item in your code sample and they both share an ID property of movieID, something like this should work:

const unlikeMovie = (state = initialState, action) => {
  switch(action.type) {
    case 'unlikeMovie': return {
      ...state,
      hearted: state.hearted.filter(item => item.movieID !== action.movie.movieID),
    }
    default: return state;
  }
}

Hope this helps!

Upvotes: 2

Related Questions