2021年4月3日星期六

state not updating when trying to paginate in react js

I am trying to fetch data from "https://reqres.in/api" and trying to paginate it. It works fine when load first time but when I am trying to paginate it I think useState() not working fine. Please help me.

You can see all the running at at this link also. https://codesandbox.io/s/sweet-mendeleev-3x4gz?file=/src/dashboard.js

  import React, { useState, useEffect } from "react";    import axios from "axios";    import base_url from "../api/baseapi"    import { func } from "prop-types";    function Dashboard() {        const [allUsers, setAllUsers] = useState([]);      const [totalPages, setTotalPages] = useState(0);      const [currentPage, setCurrentPage] = useState(1);      // const [loading, setLoading] = useState(true);      const getUserDetail = (userId) => {        console.log(userId)      }      // function to call api      const paginate = async (pageNum) => {        setCurrentPage(pageNum);      }      const getAllUsers = (currentPage) => {        axios.get(`${base_url}/users?page=${currentPage}`, {          method: 'GET',          headers: {            'Accept': 'application/json',            'Content-Type': 'application/json',          },        }).then(          (response) => {            setTotalPages(response.data.total_pages);            setAllUsers(...allUsers, response.data.data);          },          (error) => {            console.log(error)          }        ).catch(function (error) {          console.log(error);        });      }      useEffect(() => {        console.log(currentPage);        getAllUsers(currentPage);      }, [currentPage]);        let user;      console.log(allUsers)      if (allUsers.length > 0) {          user = allUsers.map(user => (          <tr key={user.id}>            <td>{user.id}</td>            <td>              <img className="img-circle" src={user.avatar} alt={user.first_name + " " + user.last_name} style= />            </td>            <td>              {user.first_name + " " + user.last_name}            </td>            <td>              <a href={`emailto:${user.email}`}>{user.email}</a>            </td>          </tr>        ));      }        // equation for patination      let renderPageNumbers = undefined;      const pageNumbers = [];      if (totalPages != null) {        for (let i = 1; i <= totalPages; i++) {          pageNumbers.push(i);        }        renderPageNumbers = pageNumbers.map(number => {          let classes = currentPage === number ? "paginate_button active" : 'paginate_button';          return (            // <span key={number} onClick={() => getAllUsers(number)}>{number}</span>            <span key={number} className={classes} onClick={() => paginate(number)}>{number}</span>          );        });      }        return (        <div className="recent-items-wp notika-shadow sm-res-mg-t-30">          <div className="rc-it-ltd">            <div className="recent-items-ctn">              <div className="recent-items-title">                <h2>All Users</h2>              </div>            </div>            <div className="dataTables_wrapper">              <table className="table table-striped dataTable">                <thead>                  <tr>                    <th>ID</th>                    <th>Photo</th>                    <th>Name</th>                    <th>Email Address</th>                  </tr>                </thead>                <tbody>                  {user}                </tbody>              </table>              <div className="dataTables_info" id="data-table-basic_info">Showing 1 to 10 of 57 entries</div>              <div className="dataTables_paginate paging_simple_numbers" id="data-table-basic_paginate">                <span onClick={() => paginate(1)} className="paginate_button previous">Previous</span>                <span>                  {renderPageNumbers}                </span>                <span onClick={() => paginate(2)} className="paginate_button next">Next</span>              </div>            </div>          </div>          <ul>          </ul>        </div>      )    }      export default Dashboard;  
https://stackoverflow.com/questions/66931638/state-not-updating-when-trying-to-paginate-in-react-js April 03, 2021 at 09:22PM

没有评论:

发表评论