I am refactoring an existing Next js project that fetches data from Contentful to render pages. At the moment it fetches the data for breadcrumbs from the getStaticProps function of every single page. I want to fetch it only from the breadcrumb component itself, using useEffect. (Most of the breadcrumb data is derived from the URL, but it is necessary to fetch some data from contentful to handle certain key words in the breadcrumbs).
I refactored the project so that the component makes the call to Contentful for the breadcrumb data, from a useEffect within the breadcrumb component. The call uses exactly the same client as it did before, and the same env vars, but returns a 404. I cannot work out why. Is it not possible to run a useEffect from a component that is shown on a page that also uses getStaticProps? Is it not possible to combine getStaticProps with client side data fetching?
breadcrumb.js:
const BreadcrumbComponent = () => {
const router = useRouter();
const path = router.asPath;
const { currentUrl, breadcrumbs } = getUrlAndBreadcrumbsFromPath(path);
const [allBreadcrumbs, setAllBreadcrumbs] = useState();
const [formattedBreadcrumbs, setFormattedBreadcrumbs] = useState();
useEffect(() => {
const getAllBreadcrumbs = async () => {
const all = await GetBreadcrumbs(); // returns a 404
setAllBreadcrumbs(all);
};
getAllBreadcrumbs();
}, []);
...
}
fetch function:
const client = createClient({
space: `${process.env.CONTENTFUL_SPACE_ID}`,
accessToken: `${process.env.CONTENTFUL_ACCESS_TOKEN}`,
environment: `${process.env.CONTENTFUL_ENVIRONMENT_NAME}`,
});
export const GetBreadcrumbs = async () => {
let response;
try {
const data = await client.getEntries({
content_type: 'breadcrumb',
});
response = data;
} catch (error) {
console.log(error);
}
return { breadcrumbs: response?.items };
};