1
votes

Exactly the whole error phrase is this.

React Hook useCallback has missing dependencies: 'params' and 'posts'. Either include them or remove the dependency array. You can also do a functional update 'setPosts(p => ...)' if you only need 'posts' in the 'setPosts' call react-hooks/exhaustive-deps Line 80:6: React Hook useEffect has missing dependencies: 'params' and 'posts'. Either include them or remove the dependency array

const [posts, setPosts] = useState([]);
  const [params, setParams] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  
  const infiniteScroll = useCallback(() => {
    let scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
    let scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
    let clientHeight = document.documentElement.clientHeight;

    if (scrollTop + clientHeight === scrollHeight && isLoading === true) {
      setIsScroll(true);
      setTimeout(function () {
        setPosts(posts.concat(posts));
        setParams((state) => state + 1);
        setIsLoading(false);
        console.log(params);
      }, 500);
    }
  }, [isLoading]);

  useEffect(() => {
    getTimeline(params).then((res) => {
      if(res.data.posts === '') {
        setIsScroll(false);
      }
      else if(posts === '' && res.data.posts === '') {
        setNotFound(false);
      }
      else {
        setNotFound(false);
        setPosts(res.data.posts);
        setIsLoading(true);
        setIsScroll(false);
      }
      
    }).catch((err) => {
            if(err.status === 403) {
                refreshToken();
            }
            else {
              if(err.status)
              {
                setStatusCode(err.status);
              }
              else setStatusCode("ERROR");
            }
        })
    window.addEventListener("scroll", infiniteScroll);
    return () => window.removeEventListener("scroll", infiniteScroll);
  }, [infiniteScroll]);

This code is an infinite scroll function that brings a new post when the screen the user sees reaches the end of the page. However, the terminal showed a compilation error like the title. How to fix it? Any help would be greatly appreciated.

1

1 Answers

0
votes

Just add a params and posts on the second parameter of your useCallback:

  const infiniteScroll = useCallback(() => {
 // ...logic
  }, [isLoading, params, posts]);

It means that you are using those variables inside the useCallback function.

It is part of react react-hooks/exhaustive-deps rule.

If you're using vscode I recommend installing linting stuff on your editor: https://github.com/facebook/react/issues/14920 so it'll warn you while coding.

If you want to disable the rule you can put // eslint-disable-next-line react-hooks/exhaustive-deps comment before the violating line if there is a good reason.

BUT, IT IS A BAD IDEA TO DISABLE IT.