I'm trying to add react lazy in my application, and for some reason, it doesn't seem to work.
The component in which I want the lazy load to work on, fetches its data from a server, then it renders the data. The problem is, the component in which the data is getting fetched, which is in the suspense tag, gets loaded before the data actually loads. Here's my code:
AnotherTest.jsx
const AnotherTest = () => {
const [toDoListData, setToDoListData] = useState([]);
useEffect(() => {
async function fetchData() {
setTimeout(async () => {
const result = await axios.get(`/api/ToDos/filter/completed`);
setToDoListData(result.data);
}, 5000);
}
fetchData();
}, []);
if (!toDoListData.length) return null;
return (
<div>
{toDoListData.map(item => {
return <div>{item.name}</div>;
})}
</div>
);
};
Test.jsx
import React, { lazy, Suspense } from 'react';
const AnotherTest = React.lazy(() => import('./AnotherTest'));
const Testing = () => {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<AnotherTest />
</Suspense>
</div>
);
};