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