skip to Main Content

I am getting some error while importing JSON file using Template literal in react typescript.


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

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

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

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

 const fetchData = (lang: string) => {
    if (lang) {
      const data = import(`../locales/${lang}.json`);
      setData(data); // its giving me error like Argument of type 'Promise<any>' is not assignable to                         parameter of type 'SetStateAction<IData[]>
    }
  };

I tried this way and I am not getting any issue but also I am not able to see data in proper way

Here is image Data Format

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

2

Answers


  1. You issue stems from import being an async function, which will always return a Promise with the data. Your fetchPrice already handles this by being an async function too, which can then await the promise as you do in setData(await priceRangeData). So a solution would be to do the same for fetchData, like so:

    const fetchData = async (lang: string) => {
      if (lang) {
        const data = await import(`../locales/${lang}.json`);
        setData(data);
      }
    };
    
    Login or Signup to reply.
  2. You just need make fetchData to be async function and make await before import(), because it return Promise. Don’t forget make type assertion.

    const fetchData = async (lang: string) => {
      if (lang) {
        const data = await import(`../locales/${lang}.json`);
        setData(data.default as IData[]);
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search