0

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>
  );
}
yavg
  • 2,761
  • 7
  • 45
  • 115

1 Answers1

0

That is because setStates calls (i.e setCurrentPage) is asynchronous by nature, meaning that an immediate console.log after setting state will not log the just-updated value. Instead, React will schedule those setState onto the next render - therefore, you can only see/access the most updated values in the next render cycle. From the official React doc

  • Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately
  • setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

You might also wanto to see an answer I have written about this problem before: React cannot update state

Bao Huynh Lam
  • 974
  • 4
  • 12