Issue
I want to fetch data, and then use pagination to pass a number back to the api URL and fetch more data by changing the value of page
.
I am fetching data in my server component like this:
// fetchData.tsx
export const fetch_data = async (page: number) => {
const response = await fetch(`https://api/data?key=${process.env.API_KEY}&page=${page}`);
const res = await response.json();
return res.results;
};
// page.tsx
export interface Card {
id: number;
name: string;
}
export default async function Home() {
const data = await fetch_data(1);
return (
<main>
// can pass data props into ClientComponent
<ClientComponent />
</main>
);
}
// ClientComponent.tsx
const data = await fetch_data(1);
// fetch does not work here because API_KEY is not available to the client.
...
return (
{data.slice(0, 20).map((data: Card ) => (
<Cards key={data.id} data={data} />
))}
// MUI Pagination.
<Pagination count={10} variant="outlined" shape="rounded" />
)
Solution
I got the outcome I wanted by following this article. First move fetchData
to pages/api
in my root directory. It looks like this now:
import { NextApiRequest, NextApiResponse } from "next";
import axios from "axios";
export default async function fetchData(
req: NextApiRequest,
res: NextApiResponse,
) {
const { page } = req.query;
const API_KEY = process.env.API_KEY;
try {
const response = await axios.get(
`https://api/data/items?key=${API_KEY}&page=${page}`,
);
const data = response.data;
res.status(200).json(data);
} catch (error) {
res.status(500).json({ message: "Error fetching data" });
}
}
Then, I made a new Component called, ClientComponent
:
"use client";
import React, { useState, useEffect } from "react";
import Pagination from "@mui/material/Pagination";
import Cards from "./Cards";
import axios from "axios";
export interface CardType {
id: number;
name: string;
}
export default async function ClientComponent() {
const [data, setData] = useState([]);
async function fetchData(page: number) {
const response = await axios.get(`/api/fetchData?page=${page}`);
const data = await response.data;
setData(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((data: CardType) => (
<Cards key={data.id} data={data} />
))}
</div>
<Pagination
count={10}
variant="outlined"
shape="rounded"
onChange={onPageChange}
/>
</div>
);
}
And finally, my Home page now look like this:
import React from "react";
import ClientComponentfrom "./components/ClientComponent";
export default async function Home() {
return (
<main>
<div>
<ClientComponent/>
</div>
</main>
);
}
Answered By - Ciaran Crowley
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.