Ciaran Crowley
Ciaran Crowley

Reputation: 419

NextJS Client component fetch request is not called on intial render

On my home page (server component), I render a bunch of cards from a client component. There is also an API fetch request in that client component. On initial render, the fetch request does now happen and no cards are rendered because of this. I have to manually trigger a refresh with state or by refreshing the page.

My home page:

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

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

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 data = await response.data;
    setGames(data.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={data.id} data={data} />
        ))}
      </div>
    </div>
  );
}

The API route 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" });
  }
}

Upvotes: 0

Views: 69

Answers (1)

AL Faiz Ahmed
AL Faiz Ahmed

Reputation: 332

If you are sure that you are getting data in Client Component fetchData function then there is a problem in setGames() there is no such state method you have to replace setData() with setGames

and also do a tweak with this line add this data?.map

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

Upvotes: 0

Related Questions