I am practicing react redux together with oMdb api. I have a method to search movies from the api and add them to a favorites list. The problem comes when I want to remove a movie from the favorites list.
Here I show you the code of the reducer
const initialState = {
favoriteMovies: [],
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case "ADD_MOVIE":
return {
...state,
favoriteMovies: [...state.favoriteMovies, action.payload]
}
case "DELETE_MOVIE":
return {
// ...state, favoriteMovies: [...state.favoriteMovies.slice(action.payload,+1),...state.favoriteMovies.slice(0, action.payload)],
...state, favoriteMovies: [...state.favoriteMovies.filter((favoriteMovie)=>favoriteMovie !==action.payload), console.log("state.favoriteMovies", state.favoriteMovies)]
}
default:
return state;
}
}
export default reducer;
(The add method works perfectly, but none the two methods that I have tried to remove from the favorites list has worked. The slice method returns only the item that I want to remove, while the filter method tells me that favorites is undefined.)
Here I show you the Sandbox where I do the action
import React, { useEffect, useState } from "react";
import SearchSection from "./SearchSection";
import Carousel from "../components/carousels/Carousel";
import CarouselItem from "../components/carousels/CarouselItem";
import { useDispatch, useSelector } from "react-redux";
import "../assets/styles/Global.css"
import { deleteMovie } from "../store/actions";
const Sandbox = () => {
const favoriteMovies = useSelector(state => state.favoriteMovies)
const dispatch = useDispatch()
return (
<div className="sandbox">
<SearchSection />
<Carousel>
{
favoriteMovies.map(favorites =>
<CarouselItem
title={favorites.Title}
image={favorites.Poster}
alt={favorites.title}
year={favorites.Year}
click={() => { dispatch(deleteMovie(favorites)) }}
/>
)}
</Carousel>
</div>
);
};
export default Sandbox;
THANKS IN ADVANCE
You should filter on id
for example instead of the full object.
When you compare objects, it will be compared by shallow reference and they will be different.
favoriteMovies: state.favoriteMovies.filter((favoriteMovie) => favoriteMovie.id !== action.payload.id)]