Discover the step-by-step guide to integrating pagination API in Next JS using getServerSideProps

I need to update a parameter that currently reads page=1, it should instead be set as page=${setPage}

Then, when the button is pressed, it triggers a change in the table data.

This is how my code looks in [table].js:

How can I achieve this? Should I use useEffect for fetching?

What would be the best approach to enable pagination by changing the page value in the table?

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('First UW Review')
                break
            }
            case 'segunda': {
                setTitle('Second UW Review')
                break
            }
            case 'seguimiento': {
                setTitle('UW Follow-up')
                break
            }
            case 'cartera': {
                setTitle('UW Portfolio')
                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  >
                            Previous
                        </Button>
                        <Button >
                            Next
                        </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)

        // Data mapping and manipulation logic goes here...

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

        // Pass data and pagination info as props to the component
        return {
            props: {
                data,
                pages
            }
        }
    }

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

export default UnderWriting;

Answer №1

If you plan on updating page numbers using queries instead of parameters, you can follow these steps:

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

To access the pageNumber value, you can retrieve it from the context.query parameter in getServerSideProps.

const { page } = context.query;

Once you have obtained the page number, you can proceed to fetch data. Rather than using the FETCH API, consider directly querying the database within the getServerSideProps function.

When the page number changes, this component will be re-rendered and getServerSideProps will fetch updated data based on the new page number.

Here is an example of pagination JSX code:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating unique sizes for each quad in Three.js using InstancedBufferGeometry and ShaderMaterial

I'm working on creating a visually dynamic scene filled with points of varying widths and heights. The challenge I'm facing is figuring out how to manipulate the vertices in the vertex shader to achieve customized sizes for each point. Here' ...

How can I search for a particular string in JavaScript?

I have a unique custom div that has been modified to function as an input element. Inside this custom div input element, there is a <p> tag with a default placeholder text. My goal is to verify whether the content of this div is empty or contains new ...

Auto-stop the EC-2 instance after a specified period of time utilizing SDK

Is it possible to automatically terminate an EC-2 instance after a specific time, such as 2 hours from when it was created? I am currently utilizing NodeJS for my AWS EC-2 operations. Is there a specific parameter that needs to be included when creating ...

Adequate dynamic object arrangement

In my pursuit using JavaScript, I am striving to fit a group of objects of set sizes into a container with a specified horizontal width, all while preserving their approximate initial order. While whitespace is not a major concern, the goal is to keep it t ...

JavaScript that Implements MVC Architecture Using C#

When working on a cshtml page within my View, I am able to easily retrieve the URL to an action using this line of code: <h1>@Url.Action("NewComment", "Case")</h1> If I include the same code in JavaScript like this: <script> alert( ...

Tips for positioning input fields and labels in both horizontal and vertical alignment

Below is the HTML code, and I want the tags to look like this: label1: input1 label2: input2 label3: input3 Instead, it currently looks like this: label1: input1 How can I modify the HTML to achieve the desired format? HTML: <div class=" ...

When working with MSAL version 0.1.3 in angularJS, it appears that there is an issue as the Msal.IdToken

Currently, I am utilizing this approach to decode the token and retrieve its expiration date. Here is the code snippet: var decode = Msal.IdToken(localStorage["msal.idtoken"]); This method is chosen to prevent the need for adding an additional jwtdecode ...

How can one create a hidden color box?

$.colorbox({ href:"/check.html", transition:"elastic", speed: 150, innerWidth:"910", iframe:true, fastIframe:false, fixedPosition:fixedPos, onComplete:function(){ var $ ...

What is the best way to create a dynamic hyperlink that leads to a detailed information page based on the specific link clicked?

I'm currently working on a web page that displays a list of users, and I want each user's name to be clickable, leading to a page with specific details about that user. I'm new to this field, so I'm unsure where to start. My idea is to ...

The Google Maps display for this page failed to load properly on the map

<!-- <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script> --> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initialize" async="" defer="defer" type="text/javascript">& ...

the cached token retrieved by adal is consistently empty

To retrieve a cached token, I am utilizing the react-adal api import { authContext, } from '../auth' const AvatarContainer = () => { getPersonPhoto(authContext) return ( <Avatar /> ) } async function getPersonPhoto(au ...

A convenient Delete Modal Component in React utilizing Reactstrap

I am currently working on implementing a reusable Delete Component using reactstrap, which can be called from other components. Below is the code for my DeleteModal: class DeleteModal extends Component { constructor(props) { super(props); this. ...

Dependency tree resolution failed during VUE installation

After pulling my project from another computer where it worked fine, I encountered an error when trying to npm install on this machine. Can someone please provide some guidance on how to resolve this issue and prevent similar problems in the future? npm ER ...

Revolutionize your rotation axis with Axis in three.js

Greetings! I am currently working with three.js and I am attempting to rotate my 3D model along the x-axis. However, when I use the following code: object.rotation.x += 0.01;, it does not produce the desired effect. The image below depicts the current ro ...

How can we replicate the 'setTimeout' feature in Node.js without causing any interruption to the event loop?

After extensive research, I have been trying to figure out how to implement non-blocking code in Node.js. However, all the examples I have come across are tied to functions that already have built-in callbacks. Therefore, I attempted to create my own funct ...

Completing Forms with KendoUI Autocomplete

I am currently working with a KendoUI Autocomplete feature within a <form>. One issue I have encountered is that if the user presses the enter key while the autocomplete options are displayed, it only closes the options without submitting the form. S ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

Adjust the color of text as you scroll

Could you provide guidance on changing the color of fixed texts in specific sections of my portfolio website? Unfortunately, I can't share my lengthy code here, but would greatly appreciate it if you could illustrate with examples. Here's a refer ...

Ensure that children elements are aligned to the bottom by setting the axis of the HTML

Elements positioned within a parent DIV typically flow from top to bottom. Even when using Javascript to add elements to the parent DIV, they maintain this top-to-bottom positioning. I am interested in achieving a bottom-to-top axis alignment within the pa ...

Implement multiple selection of parameters in React Material UI version 1.0 and handle the onChange

Currently, I am working on implementing React Material UI 1.0.0-beta.34 and encountering an issue with the Select component. My challenge lies in trying to include an extra parameter in the onChange event handler, yet it seems that only the event parameter ...