Commit 50d901cf authored by Kim, Subin's avatar Kim, Subin
Browse files

Pagination 수정 중

parent f1ca9c13
import axios from "axios";
import { baseUrl, TMDBUrl } from "../utils/baseUrl.js";
const getAllfromTM = async () => {
const getAllfromTM = async (pageNum) => {
const payload = {
params: {
pageNum: 1
pageNum
}
}
const { data } = await axios.get(`${baseUrl}/api/movie/all`, payload)
......@@ -55,10 +55,11 @@ const remove = async (movieId) => {
return data
}
const search = async ({ type, keyword }) => {
const search = async ({ type, keyword }, pageNum) => {
const payload = {
params: {
keyword
keyword,
pageNum
}
}
const { data } = await axios.get(`${baseUrl}/api/movie/search/${type}`, payload)
......
......@@ -8,39 +8,53 @@ import catchErrors from "../../utils/catchErrors.js";
const MovieEdit = () => {
const [search, setSearch] = useState({ type: "admin", keyword: "" })
const [movieList, setMovieList] = useState([])
const [totalPages, setTotalPages] = useState(0)
const [activePage, setActivePage] = useState(1)
const [error, setError] = useState("")
useEffect(() => {
getMovieList()
paginate(activePage)
}, [])
async function getMovieList() {
async function paginate(pageNum) {
try {
setError("")
const getMovieList = await movieApi.getAllfromTM()
setMovieList(getMovieList)
const { TMDBmovies, totalPage } = (search.keyword !== '') ? await movieApi.search(search, pageNum) : await movieApi.getAllfromTM(pageNum)
setActivePage(pageNum)
setTotalPages(totalPage)
setMovieList(TMDBmovies)
} catch (error) {
catchErrors(error, setError)
catchErrors(error, setError);
}
}
async function searchMovie() {
try {
setError("")
const findMovie = await movieApi.search(search)
setMovieList(findMovie)
} catch (error) {
catchErrors(error, setError)
const prevPage = () => {
if (activePage > 1) {
paginate(activePage - 1)
} else {
paginate(1);
}
}
};
const nextPage = () => {
if (activePage < totalPages) {
paginate(activePage + 1)
} else {
paginate(totalPages);
}
};
return (
<>
<div className="d-flex justify-content-md-end justify-content-center mb-3">
<Search search={search} setSearch={setSearch} handleClick={searchMovie} />
<Search search={search} setSearch={setSearch} handleClick={paginate} />
</div>
<MovieTable movieList={movieList} />
<Pagination />
<Pagination
totalPages={totalPages}
activePage={activePage}
prevPage={prevPage}
nextPage={nextPage}
paginate={paginate} />
</>
)
}
......
const Pagination = () => {
import PaginationBoot from "./PaginationBoot";
const Pagination = ({ totalPages, activePage, prevPage, nextPage, paginate }) => {
const pageWidth = 5
const section = Math.floor((activePage - 1) / pageWidth)
let startPage = section * pageWidth + 1
if (startPage < 1) startPage = 1
let endPage = startPage + pageWidth - 1
if (endPage > totalPages) endPage = totalPages
const pageNumbers = []
for (let i = startPage; i <= endPage; i++) {
pageNumbers.push(i);
}
return (
<nav className="col-12 col-md-4 offset-md-4 my-2" aria-label="Page navigation">
<ul className="pagination justify-content-center mb-0">
<li className="page-item">
<a className="page-link" href="#" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
<li className="page-item"><a className="page-link" href="#">1</a></li>
<li className="page-item"><a className="page-link" href="#">2</a></li>
<li className="page-item"><a className="page-link" href="#">3</a></li>
<li className="page-item">
<a className="page-link" href="#" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
</ul>
</nav>
<PaginationBoot>
<PaginationBoot.First
disabled={activePage <= 1}
onClick={() => paginate(1)}
/>
<PaginationBoot.Prev onClick={prevPage} disabled={activePage <= 1} />
{pageNumbers.map((number, index) => <PaginationBoot.Item
key={index}
active={activePage === number}
onClick={() => {
console.log("number", number);
paginate(number);
}}
>
{number}
</PaginationBoot.Item>
)}
<PaginationBoot.Next
onClick={nextPage}
disabled={activePage >= totalPages}
/>
<PaginationBoot.Last
disabled={activePage >= totalPages}
onClick={() => paginate(totalPages)}
/>
</PaginationBoot>
)
// return (
// <nav className="col-12 col-md-4 offset-md-4 my-2" aria-label="Page navigation">
// <ul className="pagination justify-content-center mb-0">
// <li className="page-item">
// <a className="page-link" href="#" aria-label="Previous">
// <span aria-hidden="true">&laquo;</span>
// </a>
// </li>
// <li className="page-item"><a className="page-link" href="#">1</a></li>
// <li className="page-item"><a className="page-link" href="#">2</a></li>
// <li className="page-item"><a className="page-link" href="#">3</a></li>
// <li className="page-item">
// <a className="page-link" href="#" aria-label="Next">
// <span aria-hidden="true">&raquo;</span>
// </a>
// </li>
// </ul>
// </nav>
// )
}
export default Pagination
\ No newline at end of file
import { Link } from "react-router-dom";
const PaginationBoot = ({ children }) => {
return (
<nav aria-label="page navigation">
<ul className="pagination justify-content-center py-3">{children}</ul>
</nav>
);
};
const PageItem = ({
active = false,
disabled = false,
className = "",
style,
activeLabel = "(current)",
children,
...props
}) => {
return (
<li
style={style}
className={`${className}` + " page-item " + (active ? "active " : "") + (disabled ? "disabled " : "")}
>
<Link to="#" className={"page-link border-0 shadow-none " + (active ? "rounded-circle text-white" : "text-dark")} {...props}>
{children}
</Link>
</li>
);
};
const createButton = (name, defaultValue, label = name) => {
function Button({ children, ...props }) {
return (
<PageItem {...props}>
<span aria-hidden="true">{children || defaultValue}</span>
<span className="visually-hidden">{label}</span>
</PageItem>
);
}
Button.displayName = name;
return Button;
};
PaginationBoot.First = createButton("First", <i className="bi bi-chevron-double-left"></i>);
PaginationBoot.Prev = createButton("Prev", <i className="bi bi-chevron-left"></i>);
PaginationBoot.Item = PageItem;
PaginationBoot.Next = createButton("Next", <i className="bi bi-chevron-right"></i>);
PaginationBoot.Last = createButton("Last", <i className="bi bi-chevron-double-right"></i>);
export default PaginationBoot
\ No newline at end of file
......@@ -9,7 +9,7 @@ const Search = ({ search, setSearch, handleClick }) => {
return (
<div className="d-flex">
<input className={`form-control ${search.type === "home" ? styles.searchWhite : `${styles.search}`}`} name="keyword" type="text" autoComplete="off" onChange={handleSearch} />
<i className={`bi bi-search align-self-center ${search.type === "home" ? "text-white" : "mx-2"} ${styles.icon}`} onClick={handleClick} style={{ fontSize: "1.3rem" }}></i>
<i className={`bi bi-search align-self-center ${search.type === "home" ? "text-white" : "mx-2"} ${styles.icon}`} onClick={() => handleClick(1)} style={{ fontSize: "1.3rem" }}></i>
</div>
)
}
......
......@@ -70,4 +70,13 @@ $theme-colors: map-merge($theme-colors, $custom-colors);
// .carousel-inner .carousel-item-end,
// .carousel-inner .carousel-item-start {
// transform: translateX(0);
// }
\ No newline at end of file
// }
.page-item.active .page-link {
background-color: #FEDC00;
border-color: #FEDC00;
}
.page-link:hover, .page-link:focus {
background-color: #fff;
}
\ No newline at end of file
......@@ -5,7 +5,7 @@ const { Op } = sequelize
const getListfromDB = async (req, res) => {
try {
const findAll = await Movie.findAll({ attributes: [ 'movieId', 'title', 'release_date' ] })
const findAll = await Movie.findAll({ attributes: ['movieId', 'title', 'release_date'] })
res.json(findAll)
} catch (error) {
return res.status(500).send(error.message || "영화 목록 가져오기 중 에러 발생");
......@@ -58,6 +58,7 @@ const movieforAdmin = async (req, res) => {
try {
const TMDBmovieIds = []
const TMDBmovies = req.TMDBmovies
const totalPage = req.totalPage
TMDBmovies.forEach(element => {
TMDBmovieIds.push(element.id)
})
......@@ -68,13 +69,14 @@ const movieforAdmin = async (req, res) => {
if (findDirectors.length !== 0) {
const name = findDirectors.reduce((acc, cur, idx) => {
if (idx !== 0) return acc + ', ' + cur.name
else return acc + cur.name}, '')
else return acc + cur.name
}, '')
newObj.name = name
} else newObj.name = "없음"
return newObj
}))
findDirectorResult.forEach(element => TMDBmovies.forEach(movie => {
findDirectorResult.forEach(element => TMDBmovies.forEach(movie => {
if (element.id === movie.id) movie.director = element.name
}))
const responseAfterCompare = await Movie.findAll({
......@@ -87,7 +89,7 @@ const movieforAdmin = async (req, res) => {
if (movie.existed !== true && movie.id === element.movieId) movie.existed = true
else if (movie.existed !== true) movie.existed = false
}))
return res.json(TMDBmovies)
return res.json({ TMDBmovies, totalPage })
} catch (error) {
return res.status(500).send(error.message || "영화 가져오는 중 에러 발생")
}
......@@ -100,16 +102,17 @@ const getAllMovie = async (req, res, next) => {
const monthAgo = new Date(now.setMonth(now.getMonth() - 1)).toJSON().split(/T/)[0]
const response = await axios.get(`https://api.themoviedb.org/3/discover/movie?api_key=${process.env.TMDB_APP_KEY}&language=ko-KR&region=KR&sort_by=release_date.asc&release_date.gte=${monthAgo}&page=${pageNum}`)
req.TMDBmovies = response.data.results
req.totalPage = response.data.total_pages
next()
} catch (error) {
return res.status(500).send(error.message || "영화 가져오는 중 에러 발생")
}
}
const getMovieList = async(req,res)=>{
const getMovieList = async (req, res) => {
try {
const movieList = await Movie.findAll()
const movieIds=[]
const movieIds = []
movieList.forEach(el => {
movieIds.push(el.movieId)
})
......@@ -121,7 +124,7 @@ const getMovieList = async(req,res)=>{
)
res.json(elements)
} catch (error) {
console.log(error)
return res.status(500).send(error.message || "영화 정보 가져오는 중 에러 발생")
}
}
......@@ -174,9 +177,10 @@ const findonlyTitle = async (req, res) => {
const findaboutAll = async (req, res, next) => {
try {
const { keyword } = req.query
const response = await axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${process.env.TMDB_APP_KEY}&language=kr-KR&query=${encodeURI(keyword)}&region=KR`)
const { keyword, pageNum } = req.query
const response = await axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${process.env.TMDB_APP_KEY}&language=kr-KR&query=${encodeURI(keyword)}&region=KR&page=${pageNum}`)
req.TMDBmovies = response.data.results
req.totalPage = response.data.total_pages
next()
} catch (error) {
return res.status(500).send(error.message || "영화 검색 중 에러 발생");
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment