Upon the initial render, the fetch request in the NextJS Client component is not triggered

When I load my home page, I want to display a collection of cards from a client component. However, the API fetch request in the client component does not trigger on the initial render, preventing the cards from appearing. To fix this issue, I have to manually refresh the page or update the state.

This is how my home page looks:

import React from "react";
import Client_Component from "./components/Client_Component";

export default async function Home() {
  return (
    <main>
      <div>
        <Client_Component/>
      </div>
    </main>
  );
}

Here's the code for the client component:

"use client";
import React, { useState, useEffect } from "react";
import Pagination from "@mui/material/Pagination";
import Cards from "./Cards";
import { CardType } from "../interfaces/InterfaceTypes";
import axios from "axios";

export default async function Client_Component() {
  const [data, setData] = useState([]);

  async function fetchData(page: number) {
    const response = await axios.get(`/api/fetchData?page=${page}`);
    const newData = await response.data;
    setData(newData.results);
  }

  useEffect(() => {
    fetchData(1);
  }, []);

  const onPageChange = (event: React.ChangeEvent<unknown>, value: number) => {
    fetchData(value);
  };

  return (
    <div className="mt-5 flex flex-wrap justify-center ">
      <Pagination
        count={10}
        variant="outlined"
        shape="rounded"
        onChange={onPageChange}
      />
      <div className="mt-5 flex flex-wrap justify-center px-36 py-3">
        {data.map((game: CardType) => (
          <Cards key={game.id} data={game} />
        ))}
      </div>
    </div>
  );
}

The API route can be found at pages/api/fetchData.ts:

import { NextApiRequest, NextApiResponse } from "next";
import axios from "axios";

export default async function fetch_data(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const { page } = req.query;
  const API_KEY = process.env.API_KEY;

  try {
    const response = await axios.get(
      `https://my-api.com/api/data?key=${API_KEY}&page=${page}`,
    );
    const data = response.data;

    res.status(200).json(data);
  } catch (error) {
    res.status(500).json({ message: "Error fetching data" });
  }
}

Answer №1

If you are certain that the data is being retrieved in the Client Component's fetchData function, it seems there may be an issue with setGames(). There is no state method called setData(), so you need to replace it with setGames.

Also, make a small adjustment by adding data?.map to this line:

{data?.map((game: CardType) => (
   <Cards key={data.id} data={data} />
 ))}

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

What is the process for retrieving information from Sanity?

Having trouble with creating a schema and fetching data from sanity. The console log is showing undefined. Not sure where I went wrong but suspect it's related to the schema creation. Testimonials.tsx interface Props { testimonial: [Testimonial] ...

Encountering a Lint No Nested Ternary Error while utilizing the ternary operator

Is there a way to prevent the occurrence of the "no nested ternary" error in TypeScript? disablePortal options={ // eslint-disable-next-line no-nested-ternary units=== "mm&quo ...

Leverage the state from a Context within a Class-based component

I have a Codepen showcasing my current issue. I want to utilize the class component so that I can invoke the forward function from parentComponents via ref. However, I am struggling with how to manipulate the context where the application's current st ...

Using TypeScript with Next.js getStaticProps causes errors

Currently, I am grappling with utilizing getStaticProps along with TypeScript. Initially, I attempted to achieve this using a function declaration: import { Movie } from './movies/movie' import { GetStaticProps } from 'next' export asy ...

filter failing to provide output

Issue with fetching partnername from the filter function, always returning undefined. administrationList = [ { "runid": 6, "partnerid": 2, "partnername": "test admin2", }, { "runid& ...

Having trouble with ngx-pagination's next page button not responding when clicked?

I am experiencing issues with pagination. The next page button does not function as expected, and clicking on the page number also does not work. Below is the code snippet and a Demo link for your reference. HTML <table mat-table [dataSou ...

We were unable to locate a declaration file for the module known as 'firebase-tools'

As I delve into writing my inaugural cloud function for Firebase, I find myself in need of the firebase-tools module. To bring it on board, I updated my dependencies by editing the package.json file and executing the command npm install. Next, I attempted ...

Exploring the usage of array map parameters in rxjs 6 when combined with withLatestFrom

Prior to Rxjs 6, we were able to achieve the following: interface TypeA { payload: any; } source$.pipe( withLatestFrom(source2$, (source1: TypeA, source2: TypeB) => ({ payload: source1.payload, source2 }) ), ) In the resultSelector method ...

Learn how to utilize a Library such as 'ngx-doc-viewer2' to preview *.docx and *.xlsx files within the application

After 3 days of searching, I finally found a solution to display my *.docx and *.xlxs files in my angular application. The API returns the files as blobs, so my task was to use that blob to show the file rather than just downloading it using window.open(bl ...

How to leverage tsconfig paths in Angular libraries?

While developing an Angular library, I made configurations in the tsconfig.lib.json file by adding the following setup for paths: "compilerOptions": { "outDir": "../../out-tsc/lib", "target": "es2015", "declaration": true, "inlineSources ...

The JSX Configuration in TypeScript: Comparing ReactJSX and React

When working with Typescript and React, it's necessary to specify the jsx option in the compilerOptions section of the tsconfig.json file. Available values for this option include preserve, react, react-native, and react-jsx. { "compilerOptions": { ...

Setting up a Node.js project in your local environment and making it

I need help installing my custom project globally so I can access it from anywhere in my computer using the command line. However, I've been struggling to make it work. I attempted the following command: npm install -g . and some others that I can&ap ...

Stop committing changes in Git when there are any TypeScript errors found

While working on my project in TypeScript using Visual Code, I encountered a situation where I was able to commit and push my changes to the server through Git (Azure) even though there was an error in my code causing a build failure. It made me wonder i ...

Having trouble with rendering routes in Next.js?

Encountering an error with next.js routing for non-hash routes. Some have suggested that adding a hash to the query could cause this issue. Error: Cancel rendering route Has anyone experienced this issue before and know how to resolve it? It appears to be ...

ReactJS and Redux: setting input value using properties

I am utilizing a controlled text field to monitor value changes and enforce case sensitivity for the input. In order to achieve this, I need to access the value property of the component's state. The challenge arises when I try to update this field ...

Ways to implement pagination or filtering in Next.js

Seeking a solution to incorporate pagination or filtering in my web application through traditional page routing. Is Client Side data fetching necessary? If query strings change, how can I prevent a re-render of the page content? Avoiding fetching all data ...

Nextjs google places autocomplete not providing accurate suggestions

I'm attempting to utilize Google autocomplete to retrieve the names of mosques specifically in the United Kingdom. However, the data I am receiving is global and not limited to mosques. Here is my code: import axios from "axios"; export def ...

When the first argument is missing, using a recursive constraint default can result in the incorrect inference of the second argument, especially when both arguments share the same generic

Currently, I am developing a TypeScript implementation of a recursive binary search tree (BST) data structure using generic constraints. In order to establish a default for the recursive generic variable T without directly using it in the default declarati ...

Customizing the MUI Select component with TypeScript

What seems to be the issue in this code snippet? TS2322: Type '(event: SelectChangeEvent) => void' is not assignable to type '(event: SelectChangeEvent<unknown>, child: ReactNode) => void'.   Types of parameters 'even ...

Guide on deploying a NextJS Node app on Google Cloud Platform via GitHub

I have gone through the following process: First, I installed the `Google Cloud Build app on Github and connected it to Cloud Build. Then, I configured it to work with a specific repository (which happens to be private). Next, I created a trigger in Cloud ...