Navigating through pages in Next.js

I have been working on implementing pagination for a page in my React / NextJs application using getServerSideProps.

Here is the approach I followed:

  1. Create a pagination component
  2. Redirect to a URL with updated page numbers based on user clicks
  3. Ensure that the getServerSideProps re-renders with the new page value, which currently isn't happening.

In the current code block (Server Side Props - API call):

...

I referred to this tutorial for guidance on pagination. Additionally, I modified the click method statement as follows:

...

For handling page redirection, I have implemented the following code:

...

In an attempt to solve the issue, I have tried:

  1. Adding a refreshData method to refresh props upon URL change, inspired by this article.
  2. Switching from getServerSideProps to getInitialProps, but it didn't yield the desired results.

I would greatly appreciate any help or useful resources to overcome this challenge that has been persisting for the past 3 days.

Answer №1

The issue arises due to the refreshdata function, where router.asPath will contain the current URL. The following code snippet is functioning correctly for me.

function ProductDetail({ products, page, limit }) {
  const router = useRouter();
  const pageNumClick = (page, limit) => {
    router.push({
      pathname: router.pathname,
      query: { limit: limit, page: page },
    });
  };
  return (
    <div>
      <div onClick={() => pageNumClick(parseInt(page) + 1, limit)}>Next page</div>
      <div onClick={() => pageNumClick(parseInt(page) - 1, limit)}>
        Previous page
      </div>
      {products ? JSON.stringify(products) : <></>}
    </div>
  );
}

export async function getServerSideProps({ params, query, ...props }) {
  const products = await getProducts(query.limit, query.page);
  return {
    props: {
      products: products ? products : {},
      page: query.page,
      limit: query.limit,
    },
  };
}

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

The Next.js application encounters a crash when trying to integrate Google Firebase authentication

I'm encountering an issue while trying to integrate authentication using firebase (via Google) in my next.js application, and the app crashes consistently. I will provide the code for the auth.js page component, as well as where I set up firebase and ...

transmit data retrieved from `getStaticProps` to other static pages in NextJS

While working on my project, I encountered the task of fetching a large JSON dataset from an external API within the getStaticProps function. This dataset needs to be divided into multiple parts and passed as props to numerous static pages (potentially hun ...

Instructions on transforming an img into an Image component within next.js

I have successfully implemented all the logic in this component, tailored to the <img> tag. Now, I am aiming to apply the same logic to the Image component. However, when attempting to do so, I encounter an error. TypeError: Failed to construct &apos ...

Mongoose and Next.js: Encountered Runtime Error - Cannot Access Undefined Properties (Token)

For some reason, the Model I defined is not working properly, despite being similar to another one that works without errors. Can anyone help me figure out why? If you need to see a minimal, reproducible example, check it out here. The problematic code: ...

Troubleshooting: Next JS 13/14 - Server component failing to update data upon revisiting without requiring a refresh

After attempting to retrieve the most recent liked items from a server component in next, I noticed that the data only displays when manually refreshing the page. Even when I navigate away and return, the data is not refetched automatically - however, usin ...

I'm seeing a message in the console that says "Form submission canceled because the form is not connected." Any idea why this is happening?

For the life of me, I can't figure out why this code refuses to run the handleSubmit function. Essentially, the form is supposed to take an input and execute the handleSubmit function upon submission. This function then makes a POST request to an API ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

Unlocking the contents of an array from a separate file in Next.js

I am developing a Quiz App that consists of two main pages: takeQuiz.js and result.js. My goal is to transfer the data from the multiple-choice questions (mcqs) in takeQuiz.js to be accessible in result.js. Utilizing router.replace(), I ensure that once th ...

Utilizing server-side cookies in next.js and nest.js for efficient data storage

I have been working on a small application using Next.js and Nest.js. One of the functionalities I implemented is a /login call in my client, which expects an HttpOnly Cookie from the server in response. Upon receiving a successful response, the user shoul ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

What methods can be used to prevent accessing 'res' after the resolution of getServerSideProps?

While working on my nextJS application, I encountered an error in the page file: warn - You should not access 'res' after getServerSideProps resolves. Read more: https://nextjs.org/docs/messages/gssp-no-mutating-res I tried reading the provided ...

Limiting the size of image uploads in AWS S3

Currently, I am attempting to go through the steps outlined in this repo, which involves utilizing nextjs and AWS S3 for image uploading. However, one thing that is puzzling me is the limitation of 1MB on image sizes. I'm curious as to why this restri ...

Using a JavaScript command, connect a function from one file to another file

I attempted to import a function because I want to click on <il> servies</il> and scroll to the services section on the home page. However, I simply want to click on the li element in the navbar and scroll to the service section on the home pag ...

nextAuth.js is failing to access the accessToken, returning only the values {iat, exp, jti} instead

Here is the code I am working with: import NextAuth from "next-auth" import CredentialsProvider from "next-auth/providers/credentials" export default NextAuth({ sectret:process.env.NEXTAUTH_SECRET, session: { strategy: "jw ...

Is there a way to implement absolute imports in both Storybook and Next.js?

Within my .storybook/main.js file, I've included the following webpack configuration: webpackFinal: async (config) => { config.resolve.modules = [ ...(config.resolve.modules || []), path.resolve(__dirname), ]; return ...

Utilizing client-side properties in an onClick event within Next.js framework

class homeNotLoggedIn extends React.Component { componentDidMount() { function logout(){ localStorage.clear() location.reload() } } render() { return ( <div> < ...

Unusual host value being returned by next/headers in Next.js version 13

In my current Next.js project, I am utilizing next/headers to dynamically set a baseUrl for calls to my API. const baseUrl = () => { const protocol = process?.env.NODE_ENV === "development" ? "http" : "https"; const ...

I'm receiving a 404 error on my API route in next.js - what could be causing this

What could be causing the error message "GET http://localhost:3000/api/db/getRideTypes 404 (Not Found)" when attempting to fetch data from the sanity client? Here is a snippet of code from Rideselector.js: //"use client"; import Image from &apo ...

Is there a way to personalize the appearance of Static File in nextjs?

Is there a way to customize the display of static files, particularly images? For instance, when accessing a static file on a website like this: Currently, it just shows a basic img element. Is it possible to dynamically add additional elements to that d ...

Guide to finding and saving email addresses from a string output: extracting and storing each one individually in a text file

After collecting data from multiple sources, the output I obtained is as follows: "addressId":"132234","businessEntryCount":2026},{"district":"Nordend-West","districtSlug":"frankfurt-am-main- ...