Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

next data is not loading in my pagination

So, I have been making a User Directory Website using react and redux. Now I want to do a pagination of 20users per page from my local json file and I got the first 20 page but when I click on next button the next page doesn’t load .

This is my userList.jsx:

import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setUsers } from '../store/userSlice';
import UserCard from './UserCard';
import Pagination from './Pagination';
import myData from '../data/heliverse_mock_data.json';

const UserList = () => {
  const dispatch = useDispatch();
  const users = useSelector((state) => state.users.users);
  const [currentPage, setCurrentPage] = useState(1);
  const usersPerPage = 20;
  const domainFilter = useSelector((state) => state.users.domainFilter);
  const genderFilter = useSelector((state) => state.users.genderFilter);
  const availabilityFilter = useSelector((state) => state.users.availabilityFilter);
  const searchQuery = useSelector((state) => state.users.searchQuery);

  useEffect(() => {
    dispatch(setUsers(myData));
  }, [dispatch]);

  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  

  const filteredUsers = users.filter((user) => {
    const fullName = user.first_name + user.last_name;
    let filterCondition = true;

    if (domainFilter && domainFilter !== 'All Domains' && user.domain !== domainFilter) {
      filterCondition = false;
    }
    if (genderFilter && genderFilter !== 'All Genders' && user.gender !== genderFilter) {
      filterCondition = false;
    }
    if (
      availabilityFilter &&
      availabilityFilter !== 'Both' &&
      user.available !== (availabilityFilter === 'Yes')
    ) {
      filterCondition = false;
    }
    if (searchQuery && !fullName.toLowerCase().includes(searchQuery.toLowerCase())) {
      filterCondition = false;
    }

    return filterCondition;
  });

  const totalPages = Math.ceil(filteredUsers.length / usersPerPage);
  const indexOfLastUser = currentPage * usersPerPage;
  const indexOfFirstUser = indexOfLastUser - usersPerPage;
  const currentUsers = filteredUsers.slice(indexOfFirstUser, indexOfLastUser);

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-2 gap-4 mt-8">
      {currentUsers.map((user) => (
        <UserCard key={user.id} user={user} />
      ))}
        
      <Pagination
        totalPages={totalPages}
        currentPage={currentPage}
        onPageChange={(page) => handlePageChange(page)}
      />
    </div>
  );
};

export default UserList;

this is my pagination.jsx

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setPaginationPage } from '../store/userSlice';

const Pagination = () => {
  const dispatch = useDispatch();
  const currentPage = useSelector((state) => state.users.paginationPage);
  const totalPages = useSelector((state) => state.users.totalPages);

  const handlePageChange = (page) => {
    dispatch(setPaginationPage(page));
  };

  const handleNextPage = () => {
    if (currentPage < totalPages) {
      handlePageChange(currentPage + 1);
      console.log("h")
    }
  };

  const handlePreviousPage = () => {
    if (currentPage > 1) {
      handlePageChange(currentPage - 1);
    }
  };

  const renderPaginationLinks = () => {
    const links = [];
    for (let i = 1; i <= totalPages; i++) {
      links.push(
        <button
          key={i}
          className={`px-4 py-2 rounded-md ${
            i === currentPage ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800'
          }`}
          onClick={() => handlePageChange(i)}
        >
          {i}
        </button>
      );
    }
    return links;
  };

  return (
    <div className="flex items-center">
      <button
        onClick={handlePreviousPage}
        disabled={currentPage === 1}
        className={`px-4 py-2 rounded-md mr-2 ${
          currentPage === 1 ? 'bg-gray-300 cursor-not-allowed' : 'bg-blue-500 text-white'
        }`}
      >
        Previous
      </button>
      {renderPaginationLinks()}
      <button
        onClick={handleNextPage}
        disabled={currentPage === totalPages}
        className={`px-4 py-2 rounded-md ml-2 ${
          currentPage === totalPages ? 'bg-gray-300 cursor-not-allowed' : 'bg-blue-500 text-white'
        }`}
      >
        Next
      </button>
    </div>
  );
};

export default Pagination;

this is my redux’s store userSlice.jsx

import { configureStore, createSlice } from '@reduxjs/toolkit';


const initialState = {
    users: [],
    searchQuery: '',
    domainFilter: '',
    genderFilter: '',
    availabilityFilter: '',
    paginationPage: 1,
    teamMembers: [],
    totalPages:26
};



const userSlice = createSlice({
    name: 'users',
    initialState,
    reducers: {
        setUsers: (state, action) => {
            state.users = action.payload;
        },
        setSearchQuery: (state, action) => {
            state.searchQuery = action.payload
        },
        setDomainFilter: (state, action) => {
            state.domainFilter = action.payload
        },
        setGenderFilter: (state, action) => {
            state.genderFilter = action.payload;
        },
        setAvailabilityFilter: (state, action) => {
            state.availabilityFilter = action.payload
        },
        setPaginationPage: (state, action) => {
            state.paginationPage = action.payload
        },
        addToTeam: (state, action) => {
            state.teamMembers.push(action.payload)
        },
        removeFromTeam: (state, action) => {
            state.teamMembers = state.teamMembers.filter(
                (user) => user.id !== action.payload
            )
        }
    },
    
})



const store = configureStore({
    reducer: {
        users: userSlice.reducer
    },
});

export const { setUsers, setSearchQuery, setDomainFilter, setGenderFilter, setAvailabilityFilter, setPaginationPage , addToTeam , removeFromTeam} = userSlice.actions

export default store;

I tried console logging the handleNextPage in pagination.jsx thinking there might be problem in currentPage or totalPages but this isn’t the case.

>Solution :

It looks like you’re managing the current page state in two places: once in your UserList component and again in your Redux store. This could be causing the issue.

When you click the next button, you’re updating the paginationPage in the Redux store, but the currentPage in the UserList component stays the same, so you’re seeing the same users.

Here’s a suggestion: why not remove the local currentPage state from the UserList component and use the paginationPage from the Redux store instead? You can do this by replacing const [currentPage, setCurrentPage] = useState(1); with const currentPage = useSelector((state) => state.users.paginationPage); in your UserList component.

And in your handlePageChange function, you can dispatch the setPaginationPage action instead of setting the local state. This way, both your UserList and Pagination components will be using and updating the same state in the Redux store, and your pagination should work as expected.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading