Ashwin Bhargava
Ashwin Bhargava

Reputation: 59

Intersection Observer fails to update state

I am trying to create infinite scrolling with intersection observer, but callback function fails to update state. When i scroll down i can see states's console.log output but its always same.

import React, { useEffect, useState, useRef } from 'react';

// Css
import './index.css';

// Components
import QuadColors from './colors-components/quad-colors';
import SearchBar from '../../components/searchBar';
export default function colors() {
  const [renderColorSets, setRenderColorSets] = useState(5);
  const containerRef = useRef();
  const footRef = useRef();

  // Intersection Observer
  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        setRenderColorSets(renderColorSets + 1);
        console.log(renderColorSets);
      }
    });

    observer.observe(footRef.current);
  }, []);

  return (
    <>
      <SearchBar placeholder="Color" />
      <div className="random-colors-container" ref={containerRef}>
        {[...Array(renderColorSets)].map(() => {
          return <QuadColors />;
        })}
        <div ref={footRef} />
      </div>
    </>
  );
}```

Upvotes: 1

Views: 1507

Answers (1)

Roman Bova
Roman Bova

Reputation: 54

You should give an update function to setState, not an updated value itself (cause of enclosured value within observer callback function). Try to do next:

if (entries[0].isIntersecting) {
  setRenderColorSets((prevColorSets) => prevColorSets + 1);
  console.log(renderColorSets);
}

Thus whenever you fire setState function - you have the latest value of state.

Upvotes: 0

Related Questions