I am populating a Mui Data Grid by a list that I'm fetching in useEffect. This returns a list such as objects = [ { id: 'id', name: 'name', fieldA: '12345', fieldB: '12345' }, ... ]
. I simply just save this by setObjects(objects)
in my state.
Then I use two fetches to get two lists where fieldA
and fieldB
are primary keys.
A = [ { id: '12345', name: 'A1' }, ... ]
and B....
.then((res) => setA(A))
.then((res) => setB(B))
const [A, setA] = useState([]);
const [B, setB] = useState([]);
I am building my columns such as fieldA
and fieldB
are replaced by their names from the last two fetches.
const columns = [
...
{
field: 'fieldA',
headerName: 'Field A',
width: 140,
flex: 1,
valueGetter: (params) => getNameById(params),
},
{
field: 'fieldB',
headerName: 'Field B',
width: 140,
flex: 1,
valueGetter: (params) => getNameById(params),
},
...
]
getNameById
should be called by both columns based on this
const getNameById = (params) => {
const id = params?.row?.id;
return A.find((a) => a?.id === id)?.name; // as example for A
};
But at this point A and B are both empty although the fetches are successful and I am fetching asynchronously and setting the state.
useEffect(() => {
(async = () => {
service.get('objects').then((res) => setObjects(res));
service.get('A').then((res) => setA(res));
service.get('B').then((res) => setB(res));
})();
},[]);
Data Grid doesnt show anything in the cells.
HOWEVER - If I use a hook to confirm that all fetches went through and conditionally render Data Grid, then the names are there...
So basically const [fetchedAll, setFetchedAll] = useState(false);
useEffect(() => {
(async = () => {
service.get('objects').then((res) => setObjects(res));
service.get('A').then((res) => setA(res));
// FINALLY SET FETCHED ALL
service.get('B').then((res) => setB(res)).finally(() => setFetchedAll(true));
})();
},[]);
return(
{ fetched && <DataGrid rows={objects} columns={columns} /> }
);
Am I missing something? Why are A and B empty?
Thanks!