I am trying to add pagination to my component and to do that I need to keep a slice of a list that represents the current page. However currentTopics state doesn't change to what I am seting it. What can I do here?
import React, { useEffect, useState } from 'react'
import TopicBlock from './TopicBlock';
import Pagination from './Pagination';
import './style.css'
const TopicList = (props) => {
const topics = props.topics || [];
const postsPerPage = 2;
const [currentPage, setCurrentPage] = useState(1);
const [currentTopics, setCurrentTopics] = useState([]);
useEffect(()=>{
setCurrentTopics(topics.slice(0, postsPerPage));
},[topics]);
useEffect(()=>{
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const newCurrent = topics.slice(indexOfFirstPost, indexOfLastPost)
setCurrentTopics(newCurrent);
// These two print different arrays
console.log(newCurrent);
console.log(currentTopics);
},[currentPage]);
// Change page
const paginate = pageNumber => setCurrentPage(pageNumber);
return (
<div>
<div className='topic-list'>
{currentTopics.map((topic) => {
return <TopicBlock topic={topic} />
})}
</div>
<Pagination postsPerPage={postsPerPage}
totalPosts={topics.length}
paginate={paginate} />
</div>
)
}
export default TopicList