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
const fetchPrice = async (lang: string) => {
if (lang) {
const priceRangeData = import(`../locales/${lang}.json`);
setData(await priceRangeData);
}
};
2
Answers
You issue stems from
import
being an async function, which will always return a Promise with the data. YourfetchPrice
already handles this by being an async function too, which can then await the promise as you do insetData(await priceRangeData)
. So a solution would be to do the same forfetchData
, like so:You just need make fetchData to be async function and make await before import(), because it return Promise. Don’t forget make type assertion.