-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor:extract state logic to custom Hook
- Loading branch information
1 parent
be4429e
commit d43b910
Showing
2 changed files
with
66 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<Movie[]>([]) | ||
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 | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters