1

I wrote a component called component1 as below and it is inside the parent component. The component1 is at the bottom of the page and I don't want to render it unless the user scroll down to that area. Thus I use the InView from 'react-intersection-observer' to determine if this area is in view. If so then fetch data and render data. But I get the warning: Warning: Cannot update a component from inside the function body of a different component. What is the reason of getting this warning? Is it because I set the setInView in the component?

<parent>
    <component4 />
    <component3 />
    <component2 />
    <component1 />
</parent>

const component1 = () => {
    const [inView, setInView] = React.useState(false);
    const [loading, error, data] = fetchData(inView); // hook to fetch data
    // data is an array
    const content = data.map(d => <div>{d}</div>);
    const showEmpty = true;
    if (data) {
        showEmpty = false;
    }
    return (<InView>
        {({ inView, ref }) => {
              setInView(inView);
              return (
                <div ref={ref}>
                <div>{!showEmpty && content}</div>
                </div>
            )   
    </InView>);
}
bunny
  • 1,797
  • 8
  • 29
  • 58

1 Answers1

0

As I understood you want to fetch data when the component gets in view right?

here is my solution with useEffect:

const Componet1 = () => {

  const [inView, setInView] = useState(false)
  const [myData, setMyData] = useState(null)

  useEffect(() => {
    if (inView && !myData) {
      const [loading, error, data] = fetchData(inView); // hook to fetch data
      if (data) {
        setMyData(data)
      }
    }

    return () => {
      // cleanup
    }
  }, [inView,myData])

  return (
    <InView as="div" onChange={(inView) => setInView(inView)}>
      {myData ? myData.map((d, i) => <div key={i}>{d}</div>) : 'Loading...'}
    </InView>
  );
}

Also, this fetches data just once.

b3hr4d
  • 4,012
  • 1
  • 11
  • 24