skip to Main Content

I am trying to change the page number with setCurrentPage(page) but as I click the button, the state doesn’t change at all. Tried different approaches but nothing worked.
Tried changing the number in useState(1) manually and verified the page changes.
Can someone please help me out with this?

import axios from "axios";
import { useEffect, useState } from "react";
import '../css/page.css';
import '../css/sermons.css';
import SermonModal from "./SermonModal";
import Pagination from '@mui/material/Pagination';
import Stack from "@mui/material/Stack";
import Pagenation from "./Pagenation";

export default function GetAllSermon() {

    const [sermon, setSermon] = useState({});
    const [isLoading, setIsLoading] = useState(true);
    const [currentPosts, setCurrentPosts] = useState([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [postsPerPage, setPostsPerPage] = useState(3);

    const lastPostIndex = currentPage * postsPerPage;
    const firstPostIndex = lastPostIndex - postsPerPage;

    useEffect(() => {
        axios.get(`${process.env.NEXT_PUBLIC_SERVER_URL}/sermons`)
            .then((response) => {
                setCurrentPosts(response.data.sermons.toReversed().slice(firstPostIndex, lastPostIndex));
                setSermon(response.data.sermons.toReversed());
                setIsLoading(false);
            })
            .catch((err) => {
                console.log(err);
            });
    }, []);

    const pages = [];

    for (let i = 1; i <= Math.ceil(sermon.length / postsPerPage); i++) {
        pages.push(i);
    }

    if (isLoading) return <div>Loading...</div>;

    return (
        <>
            {currentPosts.map((sermon) => (
                <div className="component_sermon_section" key={sermon._id}>
                    <div className="sermon_snap">
                        <a href='#'><img src={sermon.snap} className='sermon_snap' /></a>
                    </div>
                    <div className="sermon_info" >
                        <h3>
                            <SermonModal sermon={sermon} />
                        </h3>
                        <p className='date_time'>
                            {sermon.date.split('T')[0]} @ {sermon.session === 'First' ? '8:00 AM 
                                           1부' : null ||
                                sermon.session === 'Second' ? '09:30 AM 2부' : null ||
                                    sermon.session === 'Third' ? '11:00 AM 3부' : null} -
                                                        {sermon.preacher} 목사
                        </p>
                    </div>
                </div>))}
            {
                pages.map((page, index) => {
                    return (
                        <>
                            <button key={index} onClick={() => setCurrentPage(page)}>{page}
                            </button>
                        </>
                    );
                })
            }
        </>
    );
};;

Tried setCurrentPage to different page number but didn’t work. Expect it to change the state of currentPage.

2

Answers


  1.     useEffect(() => {
    
    const lastPostIndex = currentPage * postsPerPage;
    const firstPostIndex = lastPostIndex - postsPerPage
    
                axios.get(`${process.env.NEXT_PUBLIC_SERVER_URL}/sermons`)
                    .then((response) => {
    setCurrentPosts(response.data.sermons.toReversed().slice(firstPostIndex, lastPostIndex));
                    setSermon(response.data.sermons.toReversed());
                    setIsLoading(false);
                })
                .catch((err) => {
                    console.log(err);
                });
        }, [currentPage]);
    

    Most likely curretPage is being updated, but the situation does not change because useEffect is not updated. Try useEffect this way. If not, check whether the page variable is number. Please report the result.

    Login or Signup to reply.
  2. Put

    const lastPostIndex = currentPage * postsPerPage;
    const firstPostIndex = lastPostIndex - postsPerPage; 
    

    inside the use effect.

    useEffect(() => {
        const lastPostIndex = currentPage * postsPerPage;
        const firstPostIndex = lastPostIndex - postsPerPage;
    
        axios.get(`${process.env.NEXT_PUBLIC_SERVER_URL}/sermons`)
                .then((response) => {
                    setCurrentPosts(response.data.sermons.toReversed().slice(firstPostIndex, lastPostIndex));
                    setSermon(response.data.sermons.toReversed());
                    setIsLoading(false);
                })
                .catch((err) => {
                    console.log(err);
                });
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search