I have this piece of code that contains the value of my currentPage
:
const [currentPage, setCurrentPage] = useState(0);
this function is triggered when when I click on the buttons.
function logsPagination(page) {
setCurrentPage(page);
console.log("currentPage " + currentPage + " page" + page);
//currentPage 1 page0
//currentPage 0 page-1
//currentPage -1 page0
//currentPage 0 page13
}
why currentPage and the parameter page
in the console.logs
are differents? never are the same values. Although in theory they should have the same value, although I understand that maybe it is due to the useState
being done when the component
is rendered
.
how can I do this console.log
once setCurrentPage
is updated?
for example:
//currentPage 1 page1 //currentPage 0 page0 //currentPage -1 page-1
this is my live code:
https://codesandbox.io/s/late-meadow-ns6g6?file=/src/App.js:117-131
import React, { useState, useEffect, useRef } from "react";
export default function Table() {
const [currentPage, setCurrentPage] = useState(0);
const [maxPage, setMaxPage] = useState(0);
const [items, setItems] = useState([]);
const USERS_URL = `https://jsonplaceholder.typicode.com/posts`;
useEffect(() => {
getItems();
}, [currentPage]);
function logsPagination(page) {
setCurrentPage(page);
console.log("currentPage " + currentPage + " page" + page);
}
function getItems() {
fetch(`${USERS_URL}?page=${currentPage}&limit=5`, {
method: "GET"
})
.then((response) => response.json())
.then((data) => {
let datacustom = {
count: 13,
results: data.splice(0, 10)
};
setItems(datacustom.results);
setMaxPage(datacustom.count);
});
}
return (
<div>
<table className="table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
{items.map((item) => {
return (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.id}</td>
<td>{item.id}</td>
</tr>
);
})}
</tbody>
</table>
<section className="pagination">
<button
className="first-page-btn"
onClick={() => {
logsPagination(0);
}}
disabled={false}
>
first
</button>
<button
className="previous-page-btn"
onClick={() => {
logsPagination(currentPage - 1);
}}
disabled={false}
>
previous
</button>
<button
className="next-page-btn"
onClick={() => {
logsPagination(currentPage + 1);
}}
disabled={false}
>
next
</button>
<button
className="last-page-btn"
onClick={() => {
logsPagination(maxPage);
}}
disabled={false}
>
last
</button>
</section>
</div>
);
}