What is the best way to incorporate SWRs pagination for effectively managing pagination within a URL structure?

In an attempt to address the lack of pagination handling on the backend in this NextJS application, I proposed passing it as query parameters in the URL, like localhost:3000/patients?page=.

My initial approach was close:

import React, { useEffect } from 'react'
import PatientsTable from 'components/patients/PatientsTable'
import useSWRWithToken from 'hooks/useSWRWithToken'
import Feedback from 'components/feedback'
import { useRouter } from 'next/router'

function Patients(props) {
  // Code snippet continues...

However, the functionality of navigating to the next and previous pages stopped working:

 import React from 'react'
import { IconButton } from '@mui/material'
import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft'
import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight'
import { styled, useTheme } from '@mui/system'

const Root = styled('div')(({ theme }) => ({
  // Styling code continues...

I suspect that my useEffect hook might be conflicting with the useSWR hook, but I have no concrete evidence.

The goal is to implement the concepts outlined here: https://swr.vercel.app/docs/pagination

Below is the implementation of useSWRWithToken:

import useSWR from 'swr'
import fetchWithToken from 'libs/fetchWithToken'
import { useAppContext } from 'context'

function useSWRWithToken(endpoint: any, dependency: Boolean = true) {
  // Continued...

Furthermore, here is the component for the Patients Table:

import React, {
  useEffect,
  useState,
  useMemo,
  useCallback,
  // Other imports...
} from 'react'
import { Paper } from '@mui/material'
// More complex component code follows...

It's important to note that global state management is handled through an appReducer:

import combineReducers from 'react-combine-reducers'
import { ReactElement } from 'react'
enum ActionName {
  SET_PAGE_HEADING = 'SET_PAGE_HEADING',
  SET_TIMER_RUNNING = 'SET_TIMER_RUNNING',
  // Other action enums listed...

Answer №1

When managing your global cache, it's important to consider the current page as part of your data key. This way, you can ensure that the data is properly managed and updated when the page changes. You can achieve this by passing the current page through your hook using

useSWRWithToken(`/patients/?page${currentPage}`)
. This will allow SWR to trigger a new fetch whenever the current page changes.


const fetcher = async (key: string, id: string, pagination: number) => {
  // In your fetch function, make sure to handle the array-like key structure
  fetchWithToken(key, accessToken, [id, page: pagination])
}
const useSWRWithToken = (key, id, pagination) = {
      const { data, error, isValidating } = useSWR(
        [`patients/${id}`, id, pagination], fetcher, options
      )
  }

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

Preventing files from being compiled in the NextJS webpack configuration

Can someone assist me with configuring NextJS webpack? In my mono-repo, I share code between React-Native and NextJS. To separate OS-specific code, I've divided the web and native code as follows: (Login.web.tsx & Login.native.tsx) For instance: ...

The pagination component in React with Material-ui functions properly on a local environment, but encounters issues when deployed

Looking for some assistance with a persistent issue I've run into. Can anyone lend a hand? [x] The problem persists in the latest release. [x] After checking the repository's issues, I'm confident this is not a duplicate. Current Behavior ...

What is the best way to utilize Create-React-App interactively without incorporating Typescript?

Using Ubuntu 20.04 on WSL 2 Installed Node version 16.17.0 When I try to create my app by running the following command: npx create-next-app ninjalist I encounter a prompt asking whether I want to use TypeScript with the project, with options for Yes an ...

Troubleshooting Next JS and Redux: Fix for getInitialProps not returning props

Looking for a skilled react developer to lend a hand. Much appreciated! I'm currently navigating the balance of using redux and NEXT JS effectively without overcomplicating the setup. OBJECTIVE: Utilize getInitialProps(for SSR) to dispatch actions ...

Why isn't the page showing up on my nextjs site?

I've encountered an issue while developing a web app using nextjs. The sign_up component in the pages directory is not rendering and shows up as a blank page. After investigating with Chrome extension, I found this warning message: Unhandled Runtime ...

The functionality to scroll to the top of the page is not functioning properly in Next.js when navigating to a new page using the Link

While using Next.js, I encountered an issue where opening a new page would maintain the scroll position from the previous page. For instance, if I had scrolled to the bottom of a product listing page and clicked on a specific product, the product details p ...

What steps can I take to limit access to my API exclusively for the Frontend?

I'm in the process of creating a gaming platform, and unfortunately, there has been an exploitation of the API. How can I establish a set of "approved domains" that are allowed to access my API? The previous misuse of the API resulted in individuals ...

Having trouble setting the state of an array using NextJS useState?

I'm facing an issue where the array saved to a useState state is not updating properly. Despite properly returning values for the variable first, the variable "data" remains an empty array. Interestingly, adding a console.log("restart") statement und ...

Is it possible to configure Next.js to automatically redirect 404 errors from a nested [slug] path to the parent file?

Suppose that I have the following file structure: /store/index.ts /store/pants/[slug].ts Is it possible to redirect 404 errors to /store/ so that the user is directed to the parent directory instead of a 404 page? ...

Changing the NextJS route triggers a re-render of the _app.js file due to the usage of next-i18next serverSide

export async function getServerSideProps({ locale }) { const data = await serverSideTranslations(locale, ['apple', 'home']); return { props: data, }; } export default function IndexPage() { return <h1>Hi!< ...

Enhance website performance by optimizing pagespeed score for pages containing a Vimeo video on the initial view

I recently launched a website in NextJS 13 that is known for its impressive speed. One of the key features of the site is a video from Vimeo embedded on the first screen. To ensure that the Vimeo iframe does not negatively impact the page speed, I have ex ...

`There seems to be an unusual issue causing tailwindcss to malfunction`

It seems like my tailwindcss isn't functioning properly. Is there something I missed? tailwind.config.js /** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./app/**/*.{js,ts,jsx,tsx,mdx}", ". ...

NextJS useEffect does not pause for API response

I'm having trouble fetching the "lovedList" values when the page loads initially. The list gets updated correctly on re-rendering. How can I ensure that it waits for the list values to render the first objects from useEffect? import { Post, PostPro ...

What causes an error when CSSRulePlugin is imported in Next.js?

For my Next.js project, I decided to incorporate the GSAP library by downloading the npm version from react gsap. However, when attempting to import it using the following code: import { gsap } from "gsap"; import { CSSRulePlugin } from "gsap/CSSRulePlug ...

Creating multilingual URLs in Next.js for both Latin and non-Latin languages

Our team is embarking on creating a react web app using next.js, but we're facing a challenge with implementing multilanguage URLs. Our objective is to ensure that the same content in different languages has unique URL slugs. For instance, www.tld.com ...

Generating an HTML version of a specific nextJS page by clicking a button that includes constantly changing data

I have a current project where I am tasked with filling a template.tsx file with the information gathered from a form, and then using that data to create an HTML file which can be downloaded to the user's device. Does anyone know how I can accomplish ...

What is it about that that ticks off so many different boxes?

Hey there! I've been working on creating checkboxes within next js that iterate through each filter and its options. Fortunately, I managed to get it up and running smoothly. However, I'm encountering an issue where checking one option in a speci ...

What causes the error when I use "use client" at the top of a component in Next.js?

Whenever I include "use client" at the top of my component, I encounter the following error: event - compiled client and server successfully in 2.5s (265 modules) wait - compiling... event - compiled client and server successfully in 932 ms (265 modules) ...

What is the method to retrieve the information from a JSON response of a POST request in a Next/React application?

I am currently leveraging the Next.js API route to manage a POST request and subsequently send a response back to the frontend. To verify this process, I have utilized the Rapid API client extension and confirmed that a response is indeed being sent to the ...

What is the best way to resolve the unusual resolution issue that arises when switching from Next.js 12 to 13

Previously, I created a website using nextjs 12 and now I am looking to rebuild it entirely with nextjs 13. During the upgrade process, I encountered some strange issues. For example, the index page functions properly on my local build but not on Vercel. ...