Hey there, I recently went through a tutorial that explained dynamic importing in Next.js (https://nextjs.org/docs/advanced-features/dynamic-import) and it worked perfectly for components.
Now, I'm facing a situation where I need to fetch data dynamically. Here's the setup:
I have a simple component called MyItems
which takes in props like items
, consisting of elements with titles and categories.
What I want to achieve is dynamically importing these lists from TypeScript files located in page-data/myitems/de|en.ts, etc.
The TypeScript files export arrays after some computations, so I can't simply import JSON dynamically or look for other solutions. It's important for me to have them as coded exports like this:
export default [{name: 'somename', title: somemagic()}]
This logic resides on a page named pages/page
.
const Page = async ({t, ...props}: Props) => {
const locale = props._nextI18Next.initialLocale;
const items = (await import(`../page-data/myitems/${locale}`)).default;
console.log(items); // Outputs fine
return (
<>
<Head>
<title>dynamic test</title>
</Head>
{/*@ts-ignore*/}
<MyPage items={items} />
</>
);
};
The issue I'm encountering is that I can't return a promise to React, which means I can't export an async component.
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
So, my question now is how do I solve this dilemma? The main aim is to successfully fetch the items but since the component is returning a promise due to being async, the rest of the React functionality fails.