Search code examples
javascriptreactjscreate-react-appcontentful

Create React App + Contentful infinite request loop


I started to follow the following tutorial: https://blog.logrocket.com/using-a-headless-cms-with-react/

Unfortunately once I completed it I noticed my Network tab in chrome started going crazy AFTER I navigated to one of the child items:

Here is the reduced code version: https://codesandbox.io/s/react-contentful-hx0de?from-embed

I figured it must be how its being called from Contentful in this snippet that uses a promise to get the results:

export default function useSinglePost(slug) {
  const promise = getSinglePost(slug);

  const [post, setPost] = useState(null);
  const [isLoading, setLoading] = useState(true);

  useEffect(() => {
    promise.then(result => {
      setPost(result[0].fields);
      setLoading(false);
    });
  }, [promise]);

  return [post, isLoading];
}

But I cant figure out why I get this infinite loop of network requests.

enter image description here


Solution

  • Try something like this,

    export default function useSinglePost(slug) {
      const [post, setPost] = useState(null);
      const [isLoading, setLoading] = useState(true);
    
      useEffect(() => {
        getSinglePost(slug)
         .then(result => {
          setPost(result[0].fields);
          setLoading(false);
        });
      }, [slug]);
    
      return [post, isLoading];
    }
    

    U have const promise = getSinglePost(slug); without any memo or something. So, In the useEffect when promise resolves u perform state changes. Causing rerender. And on those rerenders promise gets redefind changes the promise. Again causing useEffect to run. Which again causes state change and rerender and heres ur infinite LOOP