Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file.


export interface IData {
  BASE_PRICE: number;
  TIER: string;
  LIST_PRICE_MIN: number;
  LIST_PRICE_MAX: number;
  DISCOUNT_PART_NUM: Discout;
}

type Discount = {
  D1RJ6LL: number;
  D1RJ8LL: number;
  D1RJALL: number;
};

const [data, setData] = useState<IData[]>([]);

 useEffect(() => {
    fetchData(lang);
  }, [lang]);

 const fetchData = (lang: string) => {
    if (lang) {
      const jsonData = import(`../locales/${lang}.json`);
      setData(jsonData); // I encountered an error saying "Argument of type 'Promise<any>' is not assignable to                         parameter of type 'SetStateAction<IData[]>"
    }
  };

I attempted this approach and did not encounter any issues, but the data is not displaying properly.

Here is an image:

const fetchPrice = async (lang: string) => {
    if (lang) {
      const priceRangeData = import(`../locales/${lang}.json`);
      setData(await priceRangeData);
    }
  };

Answer №1

It seems that your problem arises from using the import function as an asynchronous operation, which always returns a Promise containing the data. However, you have already handled this by making your fetchPrice function async and awaiting the promise before setting the data with setData(await priceRangeData). To solve the issue, you can apply the same approach to the fetchData function:

const fetchData = async (language: string) => {
  if (language) {
    const responseData = await import(`../locales/${language}.json`);
    setData(responseData);
  }
};

Answer №2

In order for the fetchData function to work properly, it is important to make it an asynchronous function and include the await keyword before the import() statement as it returns a Promise. Additionally, don't forget to apply type assertion.

const fetchData = async (language: string) => {
  if (language) {
    const responseData = await import(`../locales/${language}.json`);
    setData(responseData.default as IData[]);
  }
};

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

Utilizing shared references across react-imask, react-bootstrap, and react-hook-form for a seamless integration

I have integrated react-bootstrap and react-imask using their example with IMaskMixin as shown below: import { IMaskMixin } from 'react-imask'; import { FormControl } from 'react-bootstrap'; const MaskedFormControl = IMaskMixin(({input ...

JavaScript seems to have difficulty correctly parsing objects from JSON

Having trouble populating a Repeat Box with objects from a JSON document. Despite my efforts, it keeps duplicating the first item instead of adding each one individually. Any ideas on what might be causing this issue? Below is the code I am currently usin ...

Unusual behavior of Typescript with Storybook's addon-docs

I'm trying to integrate storybook addon-docs into my TypeScript React project. Everything seems to be almost working, but I've noticed that the file name is affecting how the props type table gets rendered. Here is my file structure: src - Butto ...

Differences between `typings install` and `@types` installation

Currently, I am in the process of learning how to integrate Angular into an MVC web server. For guidance, I am referring to this tutorial: After some research and noticing a warning from npm, I learned that typings install is no longer used. Instead, it ...

The issue arises when attempting to utilize ExpressJS middleware in conjunction with NextJS Link feature

Incorporating Next with Express routes, I have set up a scenario where /a should only be accessible to authorized individuals, while /b is open to the public. ... other imports... const app = next({ isDev }) const handle = app.getRequestHandler() async f ...

Is there a way to execute a Node 6 npm package within a Node 5.6.0 environment?

I am currently utilizing a tool called easy-sauce to conduct cross-browser JavaScript tests. Essentially, my package.json file references this tool for the test command: { "scripts": { "test": "easy-sauce" } } Everything runs smoothly when I exec ...

Fetching information from JSON file is unsuccessful

Attempting to retrieve data from a JSON source (). The goal is to extract information about each game including goals, location, and teams. However, the current code implementation seems to be ineffective. let url = "http://www.openligadb.de/api/getma ...

I need help figuring out the best way to integrate Firebase with React functional components

Currently, I am working on developing a React app using functional components instead of classes. Due to this approach, the usual this context is not available when it comes to synchronizing the database with state data (utilizing hooks). Within the funct ...

Exploring the World of Infinite Scrolling with React.js and Material_ui

I am currently working on a project using react.js As part of this project, I need to implement a board with infinite scroll similar to Facebook I have a specific question regarding this implementation. When scrolling the board and loading more posts li ...

Guide to utilizing Terser in conjunction with webpack

I am currently using Webpack 6.10.2 in combination with Vue 3.9.3. I encountered an issue with Uglify.js when running npm run build due to its inability to handle ES6 code. To work around this problem, I followed the recommendation of removing Uglify fro ...

How to stop the HTTP Basic Auth popup with AngularJS Interceptors

In the process of developing a web app using AngularJS (1.2.16) with a RESTful API, I encountered an issue where I wanted to send 401 Unauthorized responses for requests with invalid or missing authentication information. Despite having an HTTP interceptor ...

The PHP file on the server is missing the mandatory "event" parameter for the EventSource

Explaining this issue was a bit of a challenge. I've set up a Javascript EventSource object with some customized event handlers like so: var source = new EventSource('updates.php'); source.addEventListener('add', addHandler, fals ...

Displaying data-table with only the values that are considered true

Right now, I am utilizing the AgReact table to exhibit data fetched from my endpoints. The data-table is functioning properly, however, it seems to be unable to display false values received from the endpoints on the table. Below are the snippets of my cod ...

Update the content inside a <p> tag dynamically using Javascript based on the selected option

Struggling with Javascript and need some guidance. I have a select box with 4 options, and I want to update the contents of a <p> tag with an id of pricedesc based on the selected option. Here is my current code: function priceText(sel) { var l ...

Angular 4 - The Promising Outcome: How to Retrieve the Value upon Completion

Is there a way to retrieve a value from a promise and store it in a global variable? I've been attempting to accomplish this, but the global variable remains undefined. import { Injectable } from '@angular/core'; import {ActivatedRouteSnap ...

There was an issue trying to access the JSON file, as it seems that string indices

I am struggling with accessing items from a nested json file. Can someone provide some guidance? intents = {"intents": [ {"tag": "greeting", "patterns": ["Hi", "Hey", "Is anyone there?", "Hello", "Hay"], "responses": ["Hello", "Hi", "Hi there ...

Encountering issues compiling a Next.js project using hooks

I recently created a straightforward Next.js project with just one page, index.js, which looks like this: import React, { useState } from 'react'; const MyComponent = () => { const [instance, setInstance] = useState() return ( ...

Avoid the nesting of node_modules within node_modules

When executing npm install, specific node packages with nested node modules are installed. For example: -node_modules -packageA +js -node_modules <--- should be removed/ignored +jquery -packageA-sub1 +j ...

In what ways can the Material-UI theme be customized to modify the font size of labels for TextFields, Menu dropdowns, and Autocomplete components within a React application?

Currently, I am in the midst of a React project and using Material-UI to style my components. My goal is to modify the theme by adjusting the font size of certain labels such as Text Field labels, Menu dropdown labels, and Autocomplete labels. Despite my ...

Leveraging orWhere in the bookshelf JavaScript object

I encountered an issue while using bookshelf js to create a query. When implementing orWhere in the query, I received an error message. An error occurred stating 'Object has no method 'orWhere'." Below is the code snippet that led to thi ...