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

Next-auth fails to recognize a connected account following the initial login (OAuthAccountNotLinked)

I am currently using Next.js version 14 with next-auth version 4, libSQL, and drizzle orm. I am experiencing an issue where signing in only works once when the account and user are not in the database. Subsequent sign-ins then return an OAuthAccountNotLink ...

Explain what one-time typescript interfaces are

As someone who has been using React for quite some time, I am now looking to integrate Typescript into my projects. In the past, I would create large "container" objects like this: const theme = { colors: { primary: '#00f', accent: &ap ...

You are unable to call upon an object that may be of type 'undefined' in typescript

Among all the other inquiries on this topic, my issue lies with the typescript compiler seeming perplexed due to the following code snippet: if(typeof this[method] === "function"){ await this[method](req,res,next) } The error message I am en ...

Choosing and Duplicating Text in Angular

I'm attempting to give the user the ability to select a paragraph and copy it by clicking a button. However, my current code is not working as expected. I initially tried importing directives but encountered errors, prompting me to try a different met ...

Issues arise with Jest tests following the implementation of the 'csv-parse/sync' library

Currently utilizing NestJs with Nx.dev for a monorepo setup. However, I've come across an issue after installing csv-parse/sync - my Jest tests are now failing to work. Jest encountered an unexpected token Jest failed to parse a file due to non-stand ...

Combining Multiple TypeScript Declaration Files into an NPM Package for Seamless Importing with index.d.ts

I have a unique package structure that includes: myPackage/ |- types/ | |- type1.d.ts | |- type2.d.ts |- src/ | |- someUtilities.ts |- index.ts |- package.json |- tsconfig.json In my package, the index.ts file is handling imports and exports for all th ...

Encountering an issue with locating 'react-firebase-hooks'

I've been working on a project using Next.js and recently added the package called react-firebase-hooks to it. Here is an excerpt from my Package.json file: { "name": "whatsapp", "version": "0.1.0", " ...

How can we efficiently drill down different hrefs for multiple Link components back to the original Link component?

[Solution] Here is a proposed solution from @Nikhil bhatia. For an alternative approach, refer to the original post below. export default function TopNav(props) { const { data } = props return ( <StyledDiv> <nav> ...

Having difficulty accessing `props` in a React JS and Next JS application

Currently, I am developing a React application that utilizes Server Side Rendering. In this project, I am using React Js and Next Js as my primary framework. My goal is to retrieve initial props using the getServerSideProps method by consulting the documen ...

Encountered an error in NextJs where multiple children were passed to <Link> component with the same `href` while mapping

Is there an easy way to map through an array of menu items using the NextJs < Link > component? Here's the code I'm currently using: {navigation.map((item) => ( <Link key={item.name} href={item.href} className={classNam ...

Warning in VSCODE: Use caution when using experimental decorators

I have been working on an Angular2-Typescript application and created the project using angular-cli with the command: ng new myApp However, I am facing a warning issue when creating a new component with the @Component tag. I have tried to resolve this p ...

Tips for bringing in Cassandra driver types in TypeScript?

In the documentation for the Cassandra driver, they provide code examples like this: const Uuid = require('cassandra-driver').types.Uuid; const id = Uuid.random(); However, when attempting to use this in Visual Studio Code, the Uuid class type ...

Obtain accurate dispatch type by leveraging ConnectedProps in conjunction with redux-thunk

Currently, I am utilizing Redux-Toolkit and Typescript. Specifically, my goal is to implement ConnectedProps as recommended in the redux documentation. However, it appears that the dispatch type is not recognized correctly (it is identified as a normal Dis ...

Retrieve the chosen item along with its quantity

I'm currently working on building a shopping cart application similar to this example using React.js. index.js: (Sending each product to the product component) {products.length > 0 ? products.map((product) => ( <Produ ...

Storing Json data in a variable within Angular 2: a step-by-step guide

https://i.sstatic.net/2QjkJ.png Within the params.value object, there are 3 arrays containing names that I need to extract and store in a variable. I attempted to use a ForEach loop for this purpose, but encountered an issue. Can you spot what's wron ...

Setting up a project in TypeScript with Angular 2(+) and a Node/Express server is essential for successful

Searching for the optimal approach for a project similar to this: An Angular 2 (4) client coded in TypeScript A Node/Express backend also written in TypeScript Utilizing some shared (TypeScript) models accessible to both client and server code. Is it pr ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...

Rendering a component within an asynchronous function using Next.js

I'm currently learning Next.js and attempting to iterate over a collection of items in an array to pass them into a card component. However, I am facing an issue where the Card component is not rendering on the page. When I place the Card element betw ...

Customizing the colors of an Ant Design header

I am currently attempting to modify the background color of the entire header in antdesign. I believe the file containing the default settings can be found here: https://github.com/ant-design/ant-design/blob/master/components/style/themes/default.less Upo ...

After utilizing the d3-scale function to declare an object, my developer visual suddenly ceases to function

Upon completing a section of a Power BI tutorial, the developer encountered a visual that displayed nothing but a blank page (despite running correctly). Unable to pinpoint the issue, debugging was initiated. The following test code snippet for debugging w ...