I have this wrapper component which renders out a DepartmentSection for each of the key-value pairs in DEPARTMENTS. Below is the simplified code:
import React from 'react';
import DepartmentSection from './DepartmentSection';
const AllDepartmentsWrapper = () => {
export const DEPARTMENTS = {
Math: 1,
Science: 2,
//... other departments
};
return Object.keys(DEPARTMENTS).map(deptName => {
return (
<DepartmentSection
key={deptName}
name={deptName}
/>
);
});
};
export default AllDepartmentsWrapper;
Inside of each DepartmentSection, I am making an api call that fetches some data. Once the data for that section loads, the component will display the data in a graph. Here is a simplified version:
const DepartmentSection = ({ name }) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchDepartmentData(name).then( // fetch the data
resp => {
setLoading(false);
setData(resp);
}
);
}, [name]);
return (
<div>
<h1>{name}</h1>
{loading ? 'loading...' : <DataGraph data={data} />}
</div>
);
};
The way that this currently functions, each of the DepartmentSections is mounted and the api request is immediately sent. Because of this, the department charts seem to randomly appear as the data is fetched.
What I want is for the data to be fetched based on the order that the departments are listed in the DEPARTMENTS constant. So for instance, in this case the math data would be fetched and then graphed and then the science data would be fetched and graphed. I'm thinking of it as a sort of automatic lazy-load. I still want to pull the data for all departments but I want to do it top-to-bottom.
Does anyone have thoughts on how to accomplish this?
Promise.all()because I still have to wait for all of the data before displaying. And I do not want to use a classic lazy loader because the elements need to load before they are on screen