navigation menu
import { v4 as uuid } from "uuid";
import Link from "next/link";
import { getAllCategories } from "src/utils/api";
export default async function NavMenu() {
const {data: categories} = await getAllCategories();
return (
<div className="NavMenu">
<ul className="NavMenu__categories">
{categories?.map((cat) => (
<li key={uuid()} className="NavMenu__category">
<Link href={`/category/${cat.name}`} prefetch={true}>{cat.name}</Link>
</li>
))}
</ul>
</div>
);
}
category page: (opens when click on link from above)
export default async function CategoryPage({ params }) {
const { data: products } = await getProductsByCategory(params.id);
return (
<div className="CategoryPage">
<div className="CategoryPage__grid">
{products.map((product) => (
<ProductCard key={uuid()} name={product.name} price={product.price} />
))}
</div>
<div className="CategoryPage__pagination">
<Pagination />
</div>
</div>
);
}
fetching data from api function:
export async function getProductsByCategory(category) {
const url = productsURL;
const params = {
category_slug: category,
};
Object.keys(params).forEach((key) =>
url.searchParams.append(key, params[key])
);
const products = await fetchTemplate(productsURL, "GET", publicHeaders);
return products;
}
Too much time for loading items from api.
I have 15 items in api. When fetching data for a specific category page, it filters 3 items, but it takes something around 4-6 seconds to render.
When I click on link, it navigates to category page.
But it takes too much time.
I guess in such cases, I have to choose a better approach to fetching data from api.
Do you have some suggestions for improvements?
2
Answers
Solution
The problem was that for some reason, fetching data by using
category_slug
as a params works pretty slow, something ~7s, but changing params tocategory_id
solves the problem. Now it fetches data with ~1.3s . So it should be problem from API.Client-Side Data Fetching:
Consider using a client-side data fetching library like SWR or React Query to fetch data on the client side, reducing initial page load time.
Data Pagination:
Implement pagination to load a smaller set of data initially and fetch more as the user interacts with the page.
Caching:
Implement caching for API responses to serve data from the cache for previously visited categories.
Optimize API Response:
Optimize the API response to ensure efficiency and avoid sending unnecessary data.
Loading State:
Implement a loading state or skeleton UI to provide visual feedback during data fetching.
Prefetching:
Continue using prefetching strategies like the prefetch attribute in the Link component for better user experience.