diff --git a/src/pages/Search/Search.js b/src/pages/Search/Search.js index 0d6bcef..632d3f8 100644 --- a/src/pages/Search/Search.js +++ b/src/pages/Search/Search.js @@ -1,45 +1,87 @@ import './Search.css'; import {useState, useEffect} from 'react'; +import {useNavigate} from "react-router-dom"; import MovieCard from 'components/MovieCard/MovieCard.jsx'; import SearchBar from 'components/SearchBar/SearchBar.jsx'; +import Avatar from 'components/User/Avatar/Avatar.jsx'; +import { useSession } from "providers/Session"; import {searchMovies} from 'services/search.js'; - +import {addFavorites,getFavorites} from "services/favorites.js"; const Search = () => { - const [searchTerm, setSearchTerm] = useState(''); - const [movies, setMovies] = useState([]); - const startingSearch = 'Guardians of the Galaxy'; - const getSearchResult = async (title) => { - const result = await searchMovies(title); - setMovies(result); - } - - useEffect(() => { - getSearchResult(startingSearch); - setSearchTerm(startingSearch); - },[]) - - return ( -
-

MovieLand

- setSearchTerm(e)} - handleOnClick={(e) => getSearchResult(searchTerm)} - /> - {movies?.length > 0 ? ( -
- {movies.map((movie) => ( - - ))} -
- ) : ( -
-

No movies found

-
- )} -
+ const { user } = useSession(); + const navigate = useNavigate(); + const [searchTerm, setSearchTerm] = useState(''); + const [movies, setMovies] = useState([]); + const [favorites, setFavorites] = useState([]); + const startingSearch = ''; + + const getSearchResult = async (title) => { + const result = await searchMovies(title); + setMovies(result); + } + + const goToProfile = () => { + navigate('/'); + } + + const isFavorite = (movie) => favorites.find( item => + movie.imdbID === item.imdbID + ); + + const addToFavorites = async (movie) => { + if (isFavorite(movie)) return false; + let newFavorites = [...favorites] + newFavorites.push(movie) + setFavorites(newFavorites); + await addFavorites(user,newFavorites); + console.log(`added ${movie.Title} to favorites`); + } + + const removeFromFavorites = async (movie) => { + if (!isFavorite(movie)) return false; + let newFavorites = favorites.filter( item => + item.imdbID !== movie.imdbID ); + setFavorites(newFavorites); + await addFavorites(user,newFavorites); + console.log(`removed ${movie.Title} from favorites`) + } + + useEffect(() => { + getFavorites(user).then((movies) => { + setMovies(movies); + setFavorites(movies); + }); + },[user]) + + return ( +
+

MovieLand

+ goToProfile()}/> + setSearchTerm(e)} + handleOnClick={(e) => getSearchResult(searchTerm)} + /> + {movies?.length > 0 ? ( +
+ {movies.map((movie) => ( + removeFromFavorites(movie) : () => addToFavorites(movie) } + /> + ))} +
+ ) : ( +
+

No movies found

+
+ )} +
+ ); } export default Search;