1

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.

Mladen Milosavljevic
  • 1,720
  • 1
  • 12
  • 23
  • You're using `fetch` inside of your `Widget` component, right? Why don't you just move the `fetch` call to your parent component and pass the response data from `fetch` to `Widget` through props? Or you could even use `React Context API` if there would be too much prop drilling – Kapobajza Jul 01 '22 at 14:12
  • I can't do that because of the design of the api itself. Without getting in the details much I talked with backend team and we will probably redesign backend service. There are few steps i omitted from the questions. For now, children have to fetch data. – Mladen Milosavljevic Jul 01 '22 at 14:24
  • I don't see how this problem is back end related and why do children have to fetch data? – Kapobajza Jul 01 '22 at 15:01

0 Answers0