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

Cookies are currently not being stored in production for AWS Cognito

Scenario: Utilizing the amazon-cognito-identity-js SDK for authentication purposes without amplify in a project that solely requires cognito services. Locally, everything functions smoothly where tokens are received and stored using new AmazonCognitoIdent ...

Creating a spacious text box for an enhanced Ajax search feature

I'm currently working on an AJAX application that allows users to input the name of a movie, and then loads results from the database through jquery using a PHP API. However, I'm facing a challenge in implementing a text box with the following re ...

Is Javascript necessary for submitting a form to a PHP script?

In my current project, I am working on a page to edit information in a database. While I know how to create the form in HTML and the PHP script that runs on the server, I am facing a challenge with JavaScript. My understanding of JavaScript is limited, and ...

Display different images based on user selection in vue.js

I am new to working with vue.js and I'm facing a challenge. My goal is to display images of NBA players based on the selected criteria using vue.js. For instance, if the Dunk contest champion is chosen, only images of Kobe and Jordan should be display ...

OAuth authentication in Next.js

I'm brand new to Next.js and React, so I'm a little unclear on how to approach this: We're building an app with Next.js... We'll have APIs that the client-side code will call to fetch server data. My assumption is that the source code ...

What is causing the backslash character to be removed from my ajax request?

When using Ajax to call a rest endpoint, the request takes two parameters: user and permission. $.ajax({ type: 'GET', cache: false, url: "/app/Rest/4.0/UserManagement/AddPermissionToUser", data: { username: encodeURI(user ...

Enhancing a validation form with the 'onblur' event handler

Exploring the realm of JavaScript, I find myself intrigued by the concept of creating a validation form that activates upon clicking out of the input field. Implementing various techniques to integrate this feature into an existing form has been both chall ...

Convert the value of the <textarea> element to HTML encoding

Is there a way to fetch the most recent updated value entered in a textarea and encode it in HTML format? I usually use this code snippet to retrieve the value: $('textarea').val(); // works consistently across browsers However, if the value c ...

Mastering the art of utilizing drag and drop features for both columns and rows in a React Table within ReactJS

I have managed to create a React Table with columns and rows, but now I'm looking to incorporate drag and drop functionality for both. Does anyone know how I can achieve this? Feel free to check out my CodeSandbox Sample here - https://codesandbox.io ...

What is the best way to create a basic accordion using only certain table rows?

I am faced with the task of transforming a HTML table that lists various items. Each <tr> within the table contains a unique title element, but there are cases where rows can share the same title indicating their relation. My goal is to implement jQu ...

Troubleshooting webpack encore issues with importing enums from node_modules

I am faced with a challenge of utilizing an enum from a library I created in a different project. The library is developed using Vue and typescript, bundled with rollup. On the other hand, the project is built with Symfony, with the front end also using Vu ...

Attempting to create a login and registration form

Hello, I am attempting to create a form that can generate new user accounts and passwords. These values should be stored from the input tag when the user clicks on the register button. Unfortunately, I am encountering an issue where clicking the register ...

dc.js selects a chart that has already been rendered

I am attempting to manually adjust the width of a pie chart that has already been generated. The chart is constructed and displayed using an angular factory and directive, and I want to access this chart from a controller. Is there a method similar to var ...

Here's a way to run JavaScript code from a <script> tag included in an AJAX response

Currently, I am making a jQuery GET request in this format: $.get($(this).attr("href"), $(this).serialize(), null, "script"); I'm expecting the response to be enclosed in script tags. I know that the browser won't run the response if it contai ...

KnockoutJS is unable to assign a negative value to an input field

Is there a way to assign the value of an <input> as false? It seems to work fine with true. Data Model: function DataModel(){ self = this; self.Flag = ko.observable(false); }; HTML Code: <input type="text" data-bind="value:Flag"/> ...

I'm facing challenges in getting my server action to trigger. The error message that keeps popping up is unexpected submission of a React form

I have been working on developing a registration form using Next.js, react-hook-form, and Zod. Here is the code snippet for the form component: 'use client'; import { z } from "zod"; import { useRef } from "react"; import { u ...

Retrieving the Selector Value during a Change Event

Is there a way to retrieve the selector value in a change event? I attempted this approach: $("#frek_menonton_tv :input").change(function(){ $(this).selector; }); However, it only returns an empty string. Desired outcome: frek_menonton ...

The revised document now exceeds 16,777,216 in size

When attempting to add new data to an array using mongoose, I encountered two errors. Here is the code snippet in question: return await db.fileMeta.findOneAndUpdate({ username: username, 'files.fileUID': { $ne: data.fileUID } ...

choosing a date from the UICalendar

Recently, I've started exploring Angular and I'm trying to incorporate a calendar feature using ui-calendar. So far, I've managed to display a basic calendar with some events on it. Now, my goal is to allow users to click on a specific day ...

What does it mean in Javascript when b1 is undefined while o1 has a value and is equal to b1?

Having some issues getting variables to work with drop down options on a page. At first, I couldn't even extract a value from the function but managed to do so by removing "var" from o1. Strange thing is, when I type o1 into the js console on chrome i ...