how to add pagination API in Next JS with getServerSideProps

Viewed 288

I have to add a param that changes (page=1) it should be (page=${setPage})

then when you press the button that changes the data of the table.

This is how I have my code in [table].js

How can I do to change that? Or should I use useEffect for the fetch?

What would be the appropriate method to be able to change the page or add pagination to my table by changing the value of page

import React, { useState, useEffect } from 'react'
import {
    Heading,
    Box,
    Text,
    Button,
    Flex,
    Input,
    Select,
    InputGroup,
    InputLeftElement, HStack, Center
} from '@chakra-ui/react'
import { useRouter } from 'next/router'
    
import TablesData from '../../components/tables/Tablesdata'
    
const UnderWriting = (props) => {
    const { data } = props
    console.log('data', data)

    const [dataToShow, setDataToShow] = useState(data)
    const [title, setTitle] = useState('')
    const [pageIndex, setPageIndex] = useState(1)

    const router = useRouter()
    const { tabla } = router.query

    useEffect(() => {
        switch (tabla) {
            case 'primera': {
                setTitle('Primera revision de UW')
                break
            }
            case 'segunda': {
                setTitle('Segunda revision de UW')
                break
            }
            case 'seguimiento': {
                setTitle('En Seguimiento UW')
                break
            }
            case 'cartera': {
                setTitle('Cartera de UW')
                break
            }
        }
        setDataToShow(data)
    }, [tabla, data])

    return (
        <Box>
            <Box> 
                <Box color='#96A0AA' border='1px solid #DFE6EE' boxShadow='lg' overflow='hidden' rounded='lg'>
                    <TablesData data={dataToShow}  />
                </Box>
                <Center>
                    <HStack mt={5} mb={5} >
                        <Button  >
                            Anterior
                        </Button>
                        <Button >
                            Siguiente
                        </Button>
                    </HStack>
                </Center>
            </Box>
        </Box>
    );
}

export async function getServerSideProps(context) {
    const { params, res } = context
    const { tabla } = params
    // Fetch data from external API
    const apiResponse = await fetch(`${process.env.NEXT_PUBLIC_API_URL}admin/users/signup-status?page=1&page_size=25&`)
    if (apiResponse.ok) {
        let responseData = await apiResponse.json()
        console.log(responseData)

        const mapped = responseData.results.map(user => {
            return {
                ...user,
                wait_time: parseInt(user.wait_time.split(' ')[0]) || 0
            }
        })
        let data = mapped

        // prepara la data correspondiente solo a la que se solicita
        if (tabla === 'cartera') {
            data = mapped.map(user => {
                const dataUser = { ...user }
                delete dataUser.wait_time
                return dataUser
            })
        } else {
            data = mapped.filter(user => {
                if (tabla === 'primera') {
                    return user.status === 'revision'
                }
                if (tabla === 'segunda') {
                    return user.status === 'segunda'
                }
                if (tabla === 'seguimiento') {
                    return user.status === 'seguimiento' || user.status === 'caducado'
                }
            })
            if (tabla === 'primera') {
                data = data.map(user => {
                    const dataUser = { ...user }
                    delete dataUser.comments
                    return dataUser
                })
            }
        }

        //add pagination
        const totalPages = Math.ceil(responseData.count / 25)
        const pages = []
        for (let i = 1; i <= totalPages; i++) {
            pages.push(i)
        }

        // Pass data to the page via props
        return {
            props: {
                data,
                pages
            }
        }
    }

    if (res) {
        res.writeHead(301, { location: '/404' }).end()
    }
}

export default UnderWriting;
1 Answers

I assume you will be changing page numbers using query (not params).

URL: "/[table]?page=${pageNumber}"

You can read pageNumber from the context (context.query) parameter received by getServerSideProps.

const { page } = context.query;

Once you have the page number you can fetch data. Instead of using FETCH API to get data, you can directly make a database query inside the getServerSideProps function.

Whenever the page number is changed this component will be called again and the getServerSideProps function will fetch new data based on the page number.

Pagination JSX:

return(
<>
  {props.pages.map(page) => (
    <Link href={`/table?page${page}`}>
      <button>page</button>
    </Link>
  )}
</>
)
Related