Search code examples
reactjsapicontentful

I am accidentally calling the Contentful API every couple of millisenconds


I am trying to set up contentful on a react project. I have set it up and all of my data is displaying correctly, but when I go to the Network tab in devtools, I can see I'm sending API calls over and over. I tried to solve this by using isMounted but I think I must be using it wrong.

  const [aboutTypes, setAboutTypes] = useState([]);
  const { getAboutTypes } = useContentful();

  const [isMounted, setIsMounted] = useState(true);

  useEffect(() => {
    if (isMounted) {
      getAboutTypes().then((response) => response && setAboutTypes(response));

      return () => <></>;
    }
  });

  useEffect(() => {
    return () => {
      setAboutTypes(null);
      setIsMounted(false);
    };
  }, []);

useContenful.js:

const getAboutTypes = async () => {
    try {
      const entries = await client.getEntries({
        content_type: "aboutType",
        select: "fields",
      });

      const sanitizedEntries = entries.items.map((item) => {
        const typeImage = item.fields.typeImage.fields;
        return {
          ...item.fields,
          typeImage,
        };
      });

      return sanitizedEntries;
    } catch (error) {
      console.log(`Error: ${error}`);
    }
  };
  return { getAboutTypes, getHerdMembers };

Solution

  • You need to add a dependency list to useEffect, the same way you used it in the second call.

    With no dependency list, the effect is run on every render.

    useEffect(() => {
        if (isMounted) {
          getAboutTypes().then((response) => response && setAboutTypes(response));
    
          return () => <></>;
        }
      }, []); // add empty array to call once
              // or add things in the array to run every time
              // one of the items in the array changes