diff --git a/src/hooks/useMovies.tsx b/src/hooks/useMovies.tsx new file mode 100644 index 0000000..8cc3653 --- /dev/null +++ b/src/hooks/useMovies.tsx @@ -0,0 +1,53 @@ +import { useState, useEffect } from 'react' +import rviewerData from '../domain/data.json' +import { Movie } from '../domain/MovieType' +import { paginateMovies } from '../domain/movie' +import { filterMovieByTitle } from '../domain/movie' + +export default function useMovies(perPage: number) { + const [movieData, setMovieData] = useState(rviewerData) + const [currentPage, setCurrentPage] = useState(1) + const [lastPage, setLastPage] = useState(0) + const [movies, setMovies] = useState([]) + const [searchTitle, setSearchTitle] = useState('') + + useEffect(() => { + const searchedMovies = filterMovieByTitle(movieData, searchTitle) + + try { + const paginatedMovies = paginateMovies( + searchedMovies, + currentPage, + perPage, + 'releaseYear', + 'ASC' + ) + const lastPage = paginatedMovies.meta?.total_pages + if (lastPage != undefined) { + setLastPage(lastPage) + } + + setMovies(paginatedMovies.data) + } catch (err) { + if (err instanceof Error) { + console.log(err.message) + } + } + }, [currentPage, movieData, searchTitle]) + + return { + pagination: { + currentPage: currentPage, + setCurrentPage: setCurrentPage, + lastPage: lastPage + }, + movie: { + movies: movies, + setMovieData: setMovieData + }, + search: { + title: searchTitle, + setSearchTitle: setSearchTitle + } + } +} diff --git a/src/ui/Home/Home.tsx b/src/ui/Home/Home.tsx index fbc7a0e..bd3a7cd 100644 --- a/src/ui/Home/Home.tsx +++ b/src/ui/Home/Home.tsx @@ -1,56 +1,33 @@ import styles from './Home.module.css' import { Search } from '../components/Search/Search' -import React, { useState, useEffect } from 'react' -import { Movie } from '../../domain/MovieType' +import React from 'react' import Movies from '../components/Movies' -import { paginateMovies} from '../../domain/movie' import Pagination from '../components/Pagination/Pagination' -import rviewerData from '../../domain/data.json' +import useMovies from '../../hooks/useMovies' -export function Home(): React.ReactElement { - const [movieData, setMovieData] = useState(rviewerData) - const [currentPage, setCurrentPage] = useState(1) - - const [lastPage, setLastPage] = useState(0) +const ITEMS_PER_PAGE = 10 - const [movies, setMovies] = useState([]) - - useEffect(() => { - try { - const paginatedMovies = paginateMovies( - movieData, - currentPage, - 10, - 'releaseYear', - 'ASC' - ) - const lastPage = paginatedMovies.meta?.total_pages - if (lastPage != undefined) { - setLastPage(lastPage) - } +export function Home(): React.ReactElement { + const { movie, pagination, search } = useMovies(ITEMS_PER_PAGE) - setMovies(paginatedMovies.data) - } catch (err) { - if (err instanceof Error) { - console.log(err.message) - } - } - }, [currentPage, movieData]) + const handleTitleSearch = (e) => { + search.setSearchTitle(e.target.value) + } return (
- +

Popular Movies

- +
)