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>); } 
3
  • aren't you missing a return in your component ? Where is the jsx being returned? Commented Aug 20, 2020 at 18:17
  • Sorry, updated it. Commented Aug 20, 2020 at 18:27
  • I think this component should be capitalized, also the parent tag. Commented Jan 4, 2021 at 16:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.