I have an array of widgets for the app and each widget component is calling API for its data. There are multiple type of widgets, charts, lists, tables, etc.. and situation dictates that parent page cant call data itself so, children components (widgets) have to.
widgetsArr.forEach((item)=> <Widget type={item.type} widgetConfig={item.config} />)\
However there is configuration for widget position on the page, based on widgets index in array. Simple function does the trick for that part:
useEffect(() => {
if (boardsContext.customisation) {
setWidgetsArr(arrayMove(widgets, oldIndex, newIndex));
}
}, [dep1,dep2]);
// setWidgetsArray is setter for widgets array that lives on the same page as code
above.
So, what's the problem? When I setWidgetsArr again, each is fetching data again. I would like to avoid that somehow, but since state and props of parent component are changed it triggers again.
I tried with useMemo, but use memo does not accept promise inside it. Here is sample of a code:
const memoFetch = useMemo(()=>fetchChartsData(args).then((data) => isMounted &&
setData(data));, [deps])
useEffect(() => {
let isMounted = true;
//fetchChartsData(args).then((data) => isMounted && setData(data));
memoFetch()
return () => {
isMounted = false;
};
}, [dependecy]);
// this is individual Widget sample code (its not same for all the widgets but its
similar
for this paticular case I am getting:
TypeError: Cannot read properties of undefined (reading 'fetchData')
Edit: I was lookingat this question and it didn't helped me much besides reminding me that i should not use useMemo and async call with eachother.