React table loads but disappears on clicking pagination links

316 Views Asked by At

I am new to React and trying to develop my first web application. What I am trying to achieve is pretty basic. I am trying to fetch some data from an API and display it in a table. To the table I am trying to add pagination so that all the records are not displayed on the same screen. I have added the page numbers but when I click on any of the page number links, the correct data in the table gets loaded but the table disappears immediately. I have no clue why this is happening. Here is my code below:

Basket.js

import React, { useState, useEffect } from "react";
import axios from "axios";
import Posts from "../Posts";
import Pagination from "../Pagination";

const Basket = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [postsPerPage] = useState(10);

  useEffect(() => {
    const fetchPosts = async () => {
      setLoading(true);
      const res = await axios.get("http://192.168.29.135:8000/aysle/baskets/");
      setPosts(res.data);
      setLoading(false);
    };
    fetchPosts();
  }, []);
  //Get current posts
  const indexOfLastPost = currentPage * postsPerPage;
  const indexOfFirstPost = indexOfLastPost - postsPerPage;
  const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);

  //Change Page
  const paginate = (pageNumber) => setCurrentPage(pageNumber);

  //console.log(posts);
  return (
    <div>
      <Posts posts={currentPosts} loading={loading} />
      <Pagination
        postsPerPage={postsPerPage}
        totalPosts={posts.length}
        paginate={paginate}
      />
    </div>
  );
};

export default Basket;

To display the data in tabular form am using the below code: Posts.js:

import React from "react";
import edit from "../images/edit.png";
import del from "../images/delete.png";
import "./Basket/basket.scss";

const Posts = ({ posts, loading }) => {
  if (loading) {
    return <h2>Loading All Baskets....</h2>;
  }
  return (
    <table className="basket-view">
      <thead>
        <tr id="Baskettr">
          <th id="Basketth" colSpan="4">
            Here are your Listings...
          </th>
        </tr>
        <tr id="Baskettr">
          {/* <th id="Basketth">Id</th> */}
          <th id="Basketth">Basket Name</th>
          <th id="Basketth">Basket Creation Date</th>
          <th id="Basketth">Basket Modified Date</th>
          <th id="Basketth">Action</th>
        </tr>
      </thead>
      <tbody id="Baskettbody">
        {posts ? (
          posts.length > 0 ? (
            posts.map((post, index) => {
              return (
                <tr id="Baskettr" key={index}>
                  {/* <td id="Baskettd">{basket.id}</td> */}
                  <td id="Baskettd">{post.basket_name}</td>
                  <td id="Baskettd">{post.basket_creation_date}</td>
                  <td id="Baskettd">{post.basket_modified_date}</td>
                  <td>
                    <button id="delBtn" title="Edit">
                      <img src={edit} id="BtnImg" alt="Edit" />
                    </button>
                    <button id="editBtn" title="Delete">
                      <img src={del} id="BtnImg" alt="Delete" />
                    </button>
                  </td>
                </tr>
              );
            })
          ) : (
            <tr id="Baskettr">
              <td id="Baskettd">No Records to Show...</td>
            </tr>
          )
        ) : (
          0
        )}
      </tbody>
    </table>
  );
};

export default Posts;

And finally, for pagination I am using the following code:

import React from "react";

const Pagination = ({ postsPerPage, totalPosts, paginate }) => {
  const pageNumbers = [];
  //console.log(totalPosts);
  for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
    pageNumbers.push(i);
  }
  return (
    <nav>
      <ul className="pagination">
        {pageNumbers.map((number) => (
          <li key={number} className="page-item">
            <a onClick={() => paginate(number)} href="!#" className="page-link">
              {number}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
};

export default Pagination;

Please help me to rectify this issue. Thanks a lot for your time in advance. Here is the CodeSandBoxLink

1

There are 1 best solutions below

0
On

It's all because of the href attribute "!#" in the tag. Because of it, there is a transition to a new page and all data fetched again.

You can use <button/> instead of <a/> and style it with css. example