Why test.map is wrong, then how can I import the data using Promise The Jsx file is work if I just type the const data in the same file
JS file (export)
export const test = () => {
return new Promise((resolve, reject) => {
resolve(data());
});
};
const data = () => {
return [
{
name: "tom",
car: "tesla"
},
{
name: "sam",
car: "honda"
},
{
name: "may",
car: ["toyota", "BMW"],
},
];
};
Jsx file (import)
import { test } from "./test"
function List() {
return (
<div className="food">
{test.map((value,index) => (
<div key={index}>
<p>{value.name}</p>
<p>{value.car}</p>
</div>
))}
</div>
)
}
export default List
CodePudding user response:
Test
isn't an array variable, it's a function that returns a Promise object.
To fix your problem follow these steps:
Declare state
data
and initial its value to[]
.Add
useEffect
hook to fetch your data.Use state
data
to render your html.import React, { useState, useEffect } from 'react'; import { test } from './test'; function List() { const [data, setData] = useState([]); useEffect(() => { test().then((res) => setData(res)); }, []); return ( <div className="food"> {data.map((value, index) => ( <div key={index}> <p>{value.name}</p> <p>{value.car}</p> </div> ))} </div> ); } export default List;
This is a simple demo: https://stackblitz.com/edit/react-2pmxgb?file=src/App.js
CodePudding user response:
Soufiane Boutahlil answer is correct, Furthermore if you want you can also make a custom hook for functions that returns promises like so
function useAsync(promise, defaultValue) {
const [data, setData] = useState(defaultValue);
useEffect(() => {
promise.then((promiseData) => setData(promiseData));
}, [promise]);
return data;
}
then in your code you can do this
function List() { {
const testData = useAsync(test(), []); // empty array in the second parameter can be of type any
return (
<div>
{testData.map((value, index) => (
<div key={index}>
<p>{value.name}</p>
<p>{value.car}</p>
</div>
))}
</div>
);
}
Here is a working example https://stackblitz.com/edit/react-1btahu