Sharing/fetching Data Per Component In Nextjs
Solution 1:
Cool, finally, we could handle it in a next way.
First of all, taking a look at the NextJS examples for the main post page we can realize it is using a function for fetching the post and another additional post; going deep on this function, we can see it is just fetch for getting the whole data: it is not getting the data part by part using different fetch function, instead, it uses a GraphQL query to get all required data.
Following this way, we refactorize our function to get the whole names in a single object as fetching response:
exportasyncfunctiongetPageTitlesBySlugSet(slugSet) {
const data = awaitfetchAPI(
`query PageTitleBySlug($where: JSON){
pages(where: $where) {
slug
title_en
title {
title_es
title_tr
}
}
}`,
{
variables: {
where: { slug_in: slugSet },
},
}
)
return data?.pages
}
The idea is getting all pages with the slug existing in the navLinks
, but how? We can think straight to use filter(as a GraphQL feature), but testing it in the Strapi's GraphQL console, we can't see the filer options; what can we do? READ THE DOCUMENTATION, effectively, we can use field_in
to filter any object which field matches in an array value; so, passing our slug from navLinks
as a dictionary we can get all pages matching with wanted slugs:
const navProps = awaitgetPageTitlesBySlugSet(menu_links.map(({ label }) => label))
Cool, now we can get all data at once in an easier way. Cool, now we can pass navProps
to the footer and nav components as property and we will handle it in order to localize them:
{navLinks &&
Object.keys(navLinks).length !== 0 &&
menu_links.map(({ key, href, label }) => (
<Linkhref={href}key={key}passHref><MenuItem>{localizedTitle(label)}</MenuItem></Link>
))}
Cool, but still we have a problem here: sometimes going to the index give us problems because it tries to fetch using the API URL, but it just can be accessed from the server, it is not public for the client; hence, it can't fetch correctly, giving us an error.
How to solve it? Same, in the documentation it says we must use NEXT_PUBLIC_
as a prefix for each variable which we want to could be accessed from the client-side too. So, we put it and it solves our problem, now we can navigate to the index page from every page in the site.
That's all.
There is still a slow time problem which we will handle later.
Post a Comment for "Sharing/fetching Data Per Component In Nextjs"