Is there a way to efficiently import only a specific data array into a NextJs page without importing the entire component dynamically?

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.

Answer №1

After resolving the issue independently, I am sharing the solution for others encountering the same problem.

In summary, you can dynamically import a React component, but the "localized" react component depends on the common page. For instance, the page-en.tsx imports page.tsx as shown below:

This code represents your main page in NextJs:

import React from 'react';

import dynamic from 'next/dynamic';

const Page = ({ t, ...props }: Props) => {
    const locale = props._nextI18Next.initialLocale;
    const nt = scopedT(t, T_NAMESPACE);

    const DynamicComponent = dynamic(() => import(`../page-data/mypage/${locale}`));

    return (
        <>
            <Head>
                <title>{nt('pageTitle')}</title>
            </Head>
            {/*@ts-ignore*/}
            <DynamicComponent />
        </>
    );
};

and the following code represents your

page-data/mypage/en|de|whateverlang.tsx

const En: React.FC = () => {
    return <MyPage items={getItemsForLocale('en')} />;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Headers have already been sent to the client and cannot be reset

Although I am relatively new to using nodeJs, I have conducted research to troubleshoot my issue. However, it appears that I am struggling a bit with asynchronous functionalities. I came across a solution that unfortunately did not work as expected. Here i ...

Exploring Unicode Symbols for Icon Selection

I'm currently working on integrating an icon picker into my application that will enable the user to select a mathematical operator for data comparison. While I have successfully implemented the fontawesome-iconpicker on the page, I am encountering d ...

WordPress AJAX call results in a response code of zero

TL;DR: Unique - Go straight to code below for issue. You can view the demo I am working on by following this link. In my `functions.php` file, I first localize my script: function ajaxurl(){ wp_enqueue_script( 'product-selector', get_templ ...

Determine the absent information by comparing two JSON objects with JavaScript

Two JSON objects, counties and ctyIndem, are at hand. The counties object contains all the counties in a specific US State, while ctyIndem holds information about indemnities paid in that State by county, excluding those with no payments made. My task is t ...

AngularJS checkbox ng-repeat directive not displaying controller data

I am facing an issue with rendering checkbox data from the Controller file in my HTML. Here is the code snippet: HTML: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script& ...

Switch up the blogs displayed depending on the category chosen using React

I seem to have hit a roadblock with my current issue. My challenge involves organizing and displaying blog posts according to their categories: const Posts = ({ state }) => { const data = state.source.get(state.router.link); const postsPerCategory ...

Deactivating a hyperlink on my print-friendly webpage with JavaScript

My code is designed to generate a printable version of a webpage by duplicating the HTML content and then making certain modifications, such as deactivating buttons upon page load. In addition to disabling buttons, I also aim to deactivate all links on th ...

What is the best way to remove extra information from a redirect URL?

Implementing Discord login OAuth2 in JavaScript has been quite a journey. I have managed to redirect to '/auth' upon completion, but the URL for that page comes with additional information like '/auth#token_type=Bearer&access_token=12eka ...

Acquiring the item by referencing one of its property's values

Imagine you have a JSON structure that looks like this: [ { "name":"Foo" "nickname":"Lorem Ipsum" }, { "name":"Bar" "nickname":"Dolor S ...

The styles for the React calendar are not being properly applied to the calendar component due to CSS overriding

Having trouble overriding the default Calendar.css file in NextJS while creating a calendar component. Even after adding my own custom styles, they aren't being applied. Deleting the css file contents doesn't change the format either. Only when c ...

Each loop in the forEach function triggers the mouseup event

I am currently utilizing a foreach loop: objects.forEach(function(object) { var button = '<tr><td>' + object.object.code + '</td><td>' + formatDistance(1456000) + &apos ...

The attempt to add a note with a POST request to the /api/notes/addnote endpoint resulted in a

I'm facing an issue while trying to send a POST request to the /api/notes/addnote endpoint. The server is returning a 404 Not Found error. I have checked the backend code and made sure that the endpoint is correctly defined. Here are the specifics of ...

Leveraging the power of jQuery and vanilla JavaScript to create a pop-up print window for a Div element within a CMS platform that does not support media query stylesheets

I have been grappling with this particular issue for weeks now, seeking guidance from previous inquiries here. Yet, despite the helpful hints, I am still struggling to find a viable solution. My website features a scrolling sidebar measuring approximately ...

Best practices for displaying a Multidimensional JSON Object using JavaScript

Within my current project, I have a JSON object structured as follows: { "face": [ { "attribute": { "age": { "range": 5, "value": 35 }, "gender": { "confidence ...

Tips for attaching a "progress" and refresh event to an ajax call while sending a file

I am currently using the FormData API and AJAX to upload files to a server in PHP-CodeIgniter. The file upload works perfectly when triggered by the file select event. However, I would like to display a progress bar next to each file being uploaded with th ...

Design a TypeScript interface inspired by a set static array

I am working with an array of predefined strings and I need to create an interface based on them. To illustrate, here is an example of pseudo-interfaces: const options = ["option1", "option2", "option3"]; interface Selection { choice: keyof options; ...

Encountering undefined data when trying to access returned JSON data through jQuery Ajax

Utilizing the MVC approach, within my javascript code, I am encountering a discrepancy. Upon using console.log(data.msg) in the success function, the desired result is achieved. However, when attempting to employ $('#res').text("".data.msg), an ...

``When you click, the image vanishes into thin

Could you please explain why the image disappears once I close the lightbox? Access with password: chough ...

Obtaining a JWT token from local storage in a server-side component

Once the user has logged in, the API response contains a JWT token which I save in the local storage. Now, how can I access this token from the server component to make API requests? I am using Next.js 14. I am currently storing the token in a context but ...

Having an issue with the pop state function not functioning correctly

I am facing an issue with my images where clicking on a specific image changes the URL to that ID. However, I can only go back once and then the same URL is repeated every time I press the back button. Additionally, the forward button does not work at all. ...