To ensure that fetchProducts is called only once and that subsequent changes to searchParams utilize the cached response, you need to adjust your data fetching and caching strategy. Here's a comprehensive approach tailored to your Next.js app using the App Router:
-
Separate Static and Dynamic Data Fetching:
- Static Data: Data that doesn't change based on
searchParams, such as categories and subcategories, should be fetched and cached independently.
- Dynamic Data: Data that changes based on
searchParams, like the product list, should be handled separately to allow for efficient caching and retrieval.
-
Leverage React's cache Properly:
- Use
cache only on functions that benefit from caching based on their input parameters.
- Avoid wrapping higher-level functions with
cache if they internally call other cached functions, to prevent redundant caching layers.
-
Implement Singleton Pattern for Static Data:
- Ensure that static data fetching functions are called only once by defining them outside of your component's scope and wrapping them with
cache.
-
Optimize Product Fetching:
- Fetch all products initially and perform client-side filtering based on
searchParams. However, be cautious with this approach if the dataset is large, as it can impact performance.
- Alternatively, rely on server-side caching strategies where API responses are cached based on
searchParams to avoid redundant network requests.
Updated Code Implementation
Below is the revised implementation incorporating the strategies mentioned above:
// imports remain the same
import React from 'react';
import ProductList from '@/components/ProductList';
import AsyncNavBar from '@/components/AsyncNavBar';
import { cache } from 'react';
import Link from "next/link";
const ITEMS_PER_PAGE = 20;
const REVALIDATE_TIME = 14400; // 4 hours
// Helper function to construct query strings
const constructQueryParams = (params) => {
const query = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (
value !== '' &&
value !== undefined &&
value !== null &&
!Number.isNaN(value)
) {
query.set(key, value);
}
}
return query.toString();
};
// 1. Fetch static data like categories and subcategories
const fetchStaticData = cache(async () => {
const url = `https://api.naayiq.com/static-data`; // Adjust endpoint as needed
const response = await fetch(url, {
headers: { 'Content-Type': 'application/json' },
cache: 'force-cache',
next: { revalidate: REVALIDATE_TIME },
});
if (!response.ok) {
throw new Error('Failed to fetch static data');
}
return response.json();
});
// 2. Fetch products without dependency on searchParams
const fetchAllProducts = cache(async () => {
const url = `https://api.naayiq.com/products`;
const response = await fetch(url, {
headers: { 'Content-Type': 'application/json' },
cache: 'force-cache',
next: { revalidate: REVALIDATE_TIME },
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
});
// 3. The main ProductsPage component
const ProductsPage = async ({ searchParams }) => {
const {
page = '1',
query = '',
c = '',
sc = '',
b = '',
minPrice = '0',
maxPrice = '',
availability = 'all',
sortBy = '',
title = '',
} = searchParams;
// Parse numeric parameters
const pageNum = parseInt(page, 10) || 1;
const minPriceNum = parseFloat(minPrice) || 0;
const maxPriceNum = maxPrice ? parseFloat(maxPrice) : Infinity;
try {
// Fetch both static and dynamic data in parallel
const [staticData, productsData] = await Promise.all([
fetchStaticData(),
fetchAllProducts(),
]);
const products = productsData.products || [];
// Filter products based on searchParams
const filteredProducts = products.filter((product) => {
// Implement your filtering logic here
if (query && !product.name.toLowerCase().includes(query.toLowerCase())) return false;
if (c && product.category !== c) return false;
if (sc && product.subCategory !== sc) return false;
if (b && product.brand !== b) return false;
// Price filtering
const productPrices = product.sizes.map((size) => parseFloat(size.price));
const minProductPrice = Math.min(...productPrices);
const maxProductPrice = Math.max(...productPrices);
if (minProductPrice < minPriceNum) return false;
if (maxProductPrice > maxPriceNum) return false;
// Availability filtering
if (availability !== 'all' && product.availability !== availability) return false;
return true;
});
// Pagination
const totalProducts = filteredProducts.length;
const hasMore = pageNum * ITEMS_PER_PAGE < totalProducts;
const slicedProducts = filteredProducts.slice(0, pageNum * ITEMS_PER_PAGE);
// Calculate min and max price from all products
const allPrices = products.flatMap(p => p.sizes.map(s => parseFloat(s.price)));
const minPriceResult = Math.min(...allPrices);
const maxPriceResult = Math.max(...allPrices);
return (
<>
<AsyncNavBar
categories={staticData.categories}
subCategories={staticData.subCategories}
/>
<ProductList
initialProducts={slicedProducts}
totalProducts={totalProducts}
hasMore={hasMore}
initialPage={pageNum}
initialQuery={query}
initialC={c}
initialSc={sc}
initialB={b}
minPrice={minPriceResult}
maxPrice={maxPriceResult}
title={sortBy || title || 'All Products'}
/>
</>
);
} catch (error) {
// Enhanced error handling
console.error('Error fetching products:', error);
return (
<div className="font-serif flex flex-col justify-center items-center p-4">
<p>Oops! Something went wrong while loading products. Please try again later.</p>
<Link href="/" className="text-blue-500 underline mt-2">Go back home</Link>
</div>
);
}
};
export default ProductsPage;
Explanation of Changes
-
Fetching Static Data Separately:
fetchStaticData: A new cached function is introduced to fetch static data like categories and subcategories. This ensures that static data is fetched once and reused across different renderings of the ProductsPage.
- Usage: Both
categories and subCategories are passed as props to the AsyncNavBar component.
-
Fetching All Products Once:
fetchAllProducts: This function fetches all products without considering searchParams. By caching this function, it ensures that the products are fetched only once.
- Filtering: All filtering based on
searchParams is done client-side after fetching the complete product list. This avoids multiple API calls when searchParams change.
-
Optimized Error Handling:
- Enhanced the error message layout for better user experience.
- Added some basic styling to the error message container for improved visibility.
-
Improved Filtering Logic:
- Case-Insensitive Search: The query filter is now case-insensitive.
- Comprehensive Filtering: Ensured that all relevant filters (
query, category, subCategory, brand, price, and availability) are applied correctly.
-
Pagination Handling:
- The pagination logic remains the same, slicing the filtered products according to the current page.
-
Price Calculation:
- Calculated
minPriceResult and maxPriceResult from all products to ensure accurate price range displays.
Considerations
Alternative Approach: Server-Side Caching Based on searchParams
If fetching all products at once isn't feasible due to performance constraints, consider caching API responses based on searchParams. This way, fetchProducts will still be called only once per unique set of searchParams.
Here's how you can adjust your fetchProducts function:
// Fetch products with API filtering and caching based on params
const fetchProducts = cache(async (params) => {
const queryString = constructQueryParams(params);
const url = `https://api.naayiq.com/products?${queryString}`;
const response = await fetch(url, {
headers: { 'Content-Type': 'application/json' },
cache: 'force-cache',
next: { revalidate: REVALIDATE_TIME },
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
return response.json();
});
Usage in ProductsPage:
const ProductsPage = async ({ searchParams }) => {
// ...same as before
try {
// Fetch products based on current searchParams
const {
products,
totalProducts,
hasMore,
minPrice: minPriceResult,
maxPrice: maxPriceResult,
} = await getFilteredProducts({
page: pageNum,
query,
c,
sc,
b,
minPriceA: minPriceNum,
maxPriceA: maxPriceNum,
availability,
sortBy,
});
// ...rendering logic remains the same
} catch (error) {
// ...error handling remains the same
}
};
Benefits:
- Efficiency: Only unique API calls based on distinct
searchParams are made. Subsequent requests with the same parameters retrieve data from the cache.
- Scalability: Handles large datasets by fetching only what's necessary based on user filters.
- Flexibility: Allows for dynamic data fetching while still leveraging caching to minimize redundant network requests.
Conclusion
By separating static and dynamic data fetching, leveraging React's caching mechanisms appropriately, and optimizing your data fetching strategy based on your application's needs and constraints, you can ensure that fetchProducts is called only once per unique scenario, thereby enhancing performance and user experience.