Reputation: 131
I'm fetching data from node.js. So it's kinda late to get data... I guess that's why my console says 'null' all the time :/ I tried several way to fix it, but it didn't help at all.
I did use UseState but it ended up saying 'null' data. My page kept saying
TypeError: Cannot read property 'map' of null
here's my react code:
const Start = () => {
const [isLoading, setIsLoading] = useState(false);
const dataList = null;
useEffect(() => {
const getData = async () => {
setIsLoading(true);
await axios
.post('/api/getData')
.then((res) => {
console.log(res.data.result);
// 👆 at this point, this console.log says what I exactly want.
return (dataList = res.data.result);
})
.catch((err) => console.log(err));
setIsLoading(false);
};
getData();
}, []);
if (isLoading) return <div>...Loading...</div>;
return (
<div>
     Â
{dataList.map((item, idx) => (
<p>{item[0].dataName}</p>
))}
   Â
</div>
);
};
What should I do to use my data which was fetched from node.js? the data is long, large JSON.
Upvotes: 0
Views: 156
Reputation: 3244
To properly use React, you should keep data inside the state, so React's virtual DOM can properly render items according to that data (for your case).
Also, no need to chain .then
whilst using await
.
On another note, it is weird that you are using axios.post
instead of axios.get
for fetching the data, just a piece of friendly advice.
The reason why your const dataList = null
never gets updated is because you are initializing it inside the render function, meaning every time the state gets updated (setIsLoading
) your dataList
gets reinitialized to null
const Start = () => {
const [isLoading, setIsLoading] = useState(false);
const [dataList, setDataList] = useState([]);
useEffect(() => {
const getData = async () => {
setIsLoading(true);
const response = await axios.post('/api/getData');
setIsLoading(false);
setDataList(response.data.result);
};
getData();
}, []);
if (isLoading) {
return <div>...Loading...</div>;
}
return (
<div>
{dataList.map((item, idx) => (
<p>{item[0].dataName}</p>
))}
</div>
);
};
Upvotes: 2