Looking to implement a load more feature in Next.js to fetch additional data? Learn how to create a load more button for pagination using Next

Is there a way to load more data in next.js by clicking on the Load More button? Currently, I am using getServerSideProps to fetch data from an API for this page.

Here is my page code:

export default function Posts({ posts, popular }) {
  const classes = useStyles();
  return (
    <motion.main
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
    >
      <InnerWrapper pbNone>
        <Title title="Latest Post" subTitle />
      </InnerWrapper>
      <HeroSection data={posts} />
      <InnerWrapper>
        <Grid container spacing={3}>
          <Grid item xs={12} sm={8}>
            {posts.map(item => (
              <HorizontalCard key={item.id} info={item} />
            ))}

            <LoadMoreBtn />
            
          </Grid>
          <Grid item xs={12} sm={4}>
            <div className={classes.marginBottom}>
              <Title title={"Most Popular"} subTitle side={true} />
              <SideList data={popular} />
            </div>
            <div className={classes.marginBottom}>
              <SubscribeSide />
            </div>
          </Grid>
        </Grid>
      </InnerWrapper>
    </motion.main>
  );
}

export const getServerSideProps = async ({ query }) => {
  // Fetch data from external API
  const { data: posts } = await postLists(0);
  const { data: popular } = await popularPost();
  // Pass data to the page via props
  return { props: { posts, popular } };
};

Answer №1

getServerSideProps is specifically designed for fetching data to be used during the initial render of a page. However, when it comes to implementing functionality like a "load more" button that dynamically fetches additional data without reloading the entire page, you need to handle this on the client-side.

Outlined below are the steps you should follow:

  1. To effectively manage the posts that will be displayed and easily manipulate them, it's recommended to store the items in the component's state rather than passing them as props. You can achieve this by creating a state variable using useState and initializing it with the data received from the props, like so:

    const [posts, setPosts] = useState(props.posts);
    

    Going forward, make sure to use the posts variable within your component instead of relying on the prop directly.

  2. Next, integrate the "load more" button into your UI. The logic responsible for fetching and appending additional posts should be encapsulated within its onClick handler. Here's an example implementation:

    <button
      onClick={async () => {
         const newPosts = await getNewPostsFromApi();
    
         setPosts(...posts, ...newPosts);
      }}
      type="button"
    >
    Load more
    </button>
    

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

There seems to be a connection issue (ETIMEDOUT) when trying to create a React app using npm

Struggling to set up a react app with npx create-react-app my-app. Unfortunately, an error keeps popping up in the terminal: npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! network request to https://registry.npmjs.org/cr ...

Resolving type error issues related to using refs in a React hook

I have implemented a custom hook called useFadeIn import { useRef, useEffect } from 'react'; export const useFadeIn = (delay = 0) => { const elementRef = useRef<HTMLElement>(null); useEffect(() => { if (!elementRef.current) ...

React+vite application is unable to establish a WebSocket connection with a Spring Boot backend server

My React + Vite application is running on localhost:5173 port, while my Spring Boot is running on localhost:5729. Here is the code snippet from the App.jsx: import { useState } from 'react' import './App.css' function App() { const [ ...

Whenever I try to run the npm run dev function on my Ubuntu operating system, I always

After running the npm run dev function, I encountered an error. Just a day ago, everything was working fine. Can someone please help me understand why this error is occurring? Below is the full error response. I would appreciate any assistance as I have sp ...

Next.js is constantly encountering an issue where it throws an error stating "params

I've managed to establish a successful connection between my custom server using Node.js and Express.js with Next.js. The issue I'm facing is when trying to fetch a specific car by its id upon clicking it among other cars, as I keep encountering ...

Upon successfully maneuvering vendors who fail to load the NEXT.JS Link

Here is an image that is not displaying properly. The navbar's responsiveness seems to be causing the issue. return ( <Link key={index} href={'/'+item.id} > <li className="nav-item dropdown position-stati ...

Rearranging the grid table in ag-grid by relocating a newly visible column to the bottom

Seeking a solution for organizing newly added columns in a React app using ag-grid version 28.1.1. Currently, the columns are automatically sorted alphabetically upon addition from the Columns toolpanel. Is there a way to move a new column to the end of th ...

Display a Dialog when a MenuItem is selected

Is there a way to make a Dialog component appear when clicking on a MenuItem within a Material-UI Menu? In my header component, I have the following JSX being returned: return ( <AppBar iconElementLeft={<a href='/'><Avatar src="/st ...

Pictures fail to appear in https but are visible when using http

After successfully building my first personal website using the MERN stack, I encountered an issue when trying to deploy it on AWS Lightsail. While everything seemed to be working fine in HTTPS mode, the images were not displaying properly. When clicking o ...

Remove an array object in React Redux

I recently started using Redux and I’ve encountered a major issue. Whenever I try to remove an object from an array, the map function stops working. Do you have any tips or suggestions? reducer.js: const initialState = { storeState: { name: ...

Encountering a sudden MUI DatePicker Error after transitioning from Create React App to Vite for production

While my project works smoothly with CRA, I decided to switch to Vite and encountered some issues. Everything seems fine on the development server, but when I tried to go live, a problem arose on every page where I imported { DatePicker } from @mui/x-date- ...

The type 'undefined' cannot be assigned to type 'Element or null'

One of the components I am using looks like this: const data: any[] = [] <Tiers data={data}/> This is how my component is structured: const Tiers = ({ data, }: { data?: any; }) => { console.log('data', data?.length!); ...

dispatch a WebSocket message within a route using Express.js

The Objective: Imagine a bustling marketplace with multiple shops. I'm working on a dedicated page localhost:3000/livePurchases/:storeId for shop owners to receive real-time notifications whenever they make a new sale. https://i.stack.imgur.com/VdNz ...

Building a custom CellRenderer in AGGrid using TypeScript within a React environment

Currently, I am utilizing React along with TypeScript and attempting to create a custom CellRenderer in AGGrid. My code is structured like this: PriorityCellRenderer.tsx import React from 'react'; function PriorityCellRenderer(props:any) { co ...

The specified project directory was not detected. Please restart Next.js in your updated directory

I am facing a challenge with running my NextJS web app on a VPS server with PM2 as the Process Management tool. Despite trying different approaches, I am unable to get it to run properly. I have a deploy.js file that successfully deploys my other NextJS an ...

Adjust the transparency and add animation effects using React JS

When working on a React project, I encountered an issue where a square would appear under a paragraph when hovered over and disappear when no longer hovered. However, the transition was too abrupt for my liking, so I decided to implement a smoother change ...

Performing asynchronous operations in React with axios using loops

On the backend, I have a socket set up to handle continuous requests from the server. Now, my goal is to send requests to the backend API continuously until a stop button is clicked. Using a loop for this task is considered bad practice as it never checks ...

Error: The forward function is not accessible in nextjs due to an ApolloError

Help needed with resolving the ApolloError: forward is not a function problem. I have followed the documentation and tried adding an error code, but nothing seems to be working. Please assist! apollo.client.ts import { ApolloClient, InMemoryCache } from ...

Error: Unable to extract 'blog' property from 'param' because it is not defined in the Strapi NextJS context

I'm currently developing a blog using NextJS and Strapi. While implementing the comment functionality for my blog posts, I encountered two strange errors: TypeError: Cannot destructure property 'blog' of 'param' as it is undefined. ...

Is it possible to customize the color of icons in react's Material-table?

I'm currently utilizing the material-table library and I'm struggling to individually change the color of each icon. Could you assist me with this? I attempted custom CSS, but it's affecting all icons at once instead of specific ones. Here i ...