Next.js Discord

Discord Forum

generateMetadata API invocation duplication

Answered
Baldfaced hornet posted this in #help-forum
Open in Discord
Avatar
Baldfaced hornetOP
I will provide code snippet that duplicates my request. I use it in generateMetadata and async component. How can I make it not to duplicate request in this case ?

const getProductBySlug = ({ slug }) => axiosInstance.get(`/product/${slug}`);

export async function generateMetadata({ params }) {
  const { slug } = params;
  const { data } = await getProductBySlug({ slug });

  return { title: data.title };
}

async function ProductPage({ params: { slug } }) {
  const data = await getProductBySlug({ slug });
  return <div>...data</div>;
}
Answered by joulev
import { cache } from "react"

const getProductBySlug = cache(({ slug }) => axiosInstance.get(`/product/${slug}`));

or [just use fetch instead of axios](https://adios-axios.com)
View full answer

10 Replies

Avatar
have you consider adding new endpoint to get product title by slug?
Avatar
import { cache } from "react"

const getProductBySlug = cache(({ slug }) => axiosInstance.get(`/product/${slug}`));

or [just use fetch instead of axios](https://adios-axios.com)
Answer
Avatar
Baldfaced hornetOP
@joulev Good job man. Thank you. I wasn't aware of the things provided by article
Avatar
Baldfaced hornetOP
@joulev even when using cache it does not work. sad thing is that it does not work when using fetch too..
Avatar
During build or runtime?

During build, deduplication just doesn’t work at all, this is a rather low priority bug.
Avatar
Baldfaced hornetOP
During runtime
Avatar
Interesting. I’ll have a look when I have time
Avatar
Baldfaced hornetOP
Thanks. I have logs in my API and everything happens twice, 2 logs, 2 calls on the db.. 😦
Doesn't matter if you use fetch or cache, same happens
Avatar
Baldfaced hornetOP
@joulev I found what is the problem. In my function I am passing object as the parameter. Since I am calling it from 2 different places, it is always passing different object and that is why it is not using it from the cache. Once I changed my function to
const getProductBySlug = cache(
  (
    slug,
    Cookie
    // original_keys = 0,
    // update_views = true
  ) => ...


it worked