I have a listing page of Products that I intend to server render. So using NextJs's getInitialProps I fetch the list of Products and pass it on to the components and it works.
There is a requirement, whenever a city changes(from Dropdown) in client-side, I need to refetch the updated list of Products from the API. Hence, I have this API call in a useEffect. This is somewhat the idea.
ProductsWrapper.getInitialProps = async () => {
// This runs on Server Side
// fetch list of Products
const products = await getProducts();
// update the redux store with products returned from server by dispatching
return { products };
}
// Products is a redux connected component that listens for Product and City state updates
function Products({ products, city }) {
// fetch new Products iff city changes
useEffect( async () => {
// This runs only on Browser
const products = await getProducts();
// update the redux store with products returned from server
}, [city])
}
The problem is at step 3 below,
- At the server Products API call is made and fed to Redux.
- The Page is built at the server-side and sent over to the client.
- At the Client, useEffect runs and unnecessarily calls the API endpoint again.
How do I Prevent this redundant call, the first time when the page is rendered on the client?
Well, just an if check inside useEffect whether data is present before making the api call doesn't work, because despite Products data being present in Redux store, if the city changes, the api call has to be made.
awaitwithoutasync?getProductsin the city change handler?