usePagination
. В результате страничка с пагинацией тупо фризит. К слову реализация без хука работает нормально. Признаюсь, я первый раз пишу пользовательский хук, мне казалось что он чертовски хорош пока я не запустил проект. Прикрепляю ссылку на CodePen export const usePagination = (users, defaultPage = 1, amountPerPage = 10) => {
const [currentPage, setCurrentPage] = useState(defaultPage);
const [postsPerPage] = useState(amountPerPage);
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
let currentPosts = [];
let amountOfPages = 0;
if (Array.isArray(users)) {
currentPosts = users.slice(indexOfFirstPost, indexOfLastPost);
amountOfPages = Math.ceil(users.length / postsPerPage);
}
console.log(currentPosts, amountOfPages);
return {
setCurrentPage,
amountOfPages,
currentPosts,
};
};
export function ListOfItems() {
const users = useSelector(state => state);
const { setCurrentPage, currentPosts, amountOfPages } = usePagination(users);
// много кода...
return (
<div>
<Pagination amountOfPages={amountOfPages} setCurrentPage={setCurrentPage}/>
</div>
)
const Pagination = ({amountOfPages, setCurrentPage}) => {
const pageNumber = [];
for (let i = 1; i <= amountOfPages; i++) {
pageNumber.push(i);
console.log(i)
}
return (
<nav>
<ul className="pagination">
{pageNumber.map(number => (
<li key={number} className="page-item">
<button
onClick={() => {setCurrentPage(number)}}
type="button"
className="page-link"
>
{number}
</button>
</li>
))}
</ul>
</nav>
)
};
export const usePagination = (users = [], defaultPage = 1, amountPerPage = 10) => {
const [currentPage, setCurrentPage] = useState(defaultPage);
const [currentPosts, setCurrentPosts] = useState([]);
const [amountOfPages, setAmountOfPages] = useState(0);
useEffect(() => {
updatePosts();
updateAmountOfPages();
}, []);
const updatePosts = () => {
const indexOfLastPost = currentPage * amountPerPage;
const indexOfFirstPost = indexOfLastPost - amountPerPage;
const updatedUsers = users.slice(indexOfFirstPost, indexOfLastPost);
setCurrentPosts(updatedUsers);
};
const updateAmountOfPages = () => {
const updatedAmount = Math.ceil(users.length / amountPerPage);
setAmountOfPages(updatedAmount);
};
return {
setCurrentPage,
amountOfPages,
currentPosts,
};
};
const Pagination = ({amountOfPages, setCurrentPage}) => {
const [pageNumbers, setPageNumbers] = useState([]);
useEffect(() => {
calculatePageNumbers();
}, [amountOfPages]);
function calculatePageNumbers() {
const updatedPageNumbers = [];
for (let i = 1; i <= amountOfPages; i++) {
updatedPageNumbers.push(i);
}
setPageNumbers(updatedPageNumbers);
}
function handleSetCurrentPage(number) {
return () => {
setCurrentPage(number);
}
}
return (
<nav>
<ul className="pagination">
{pageNumbers.map(number => (
<li key={number} className="page-item">
<button
onClick={handleSetCurrentPage(number)}
type="button"
className="page-link"
>
{number}
</button>
</li>
))}
</ul>
</nav>
);
};