#API fetch infinite loop

2 messages · Page 1 of 1 (latest)

dawn canyon
#

Hi everyone,

A small description of what i'm trying to build, it's where a user can select a date range and then it should filter the available objects and show that to them. Now i'm getting a infinite loop here and im not quite sure how to solve this. This all happens on the client side and it happens whenever i add getAvailableObjects to the useEffect dependancy, it wont do this when i remove it, but then i get the warning i need to add it.

Down below is the code, i hope someone can help me out a bit. Im kinda new to all this, so this might looks bad at all..

const getAvailableObjects = useCallback(async () => {
    setIsLoading(true);
    try {
      const res = await fetch("api/prices", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ typeIds, fromDate, tillDate, rentalIds, composition }),
      });
      const { data } = await res.json();
      if (data) {
        const updatedObjectTypes = objects
          .map((object: any) => {
            const matchingPrice = data.find((price: any) => price.id === object.type_id);
            if (matchingPrice) {
              const { pricing, objects: availability } = matchingPrice;
              return {
                ...object,
                pricing,
                availability,
                bookable: true,
              };
            }
          })
          .filter(Boolean)
          .sort((a: any, b: any) => (b.bookable ? 1 : -1));
        setAvailableObjects(updatedObjectTypes);
        setIsLoading(false);
      }
      return data;
    } catch (error) {
      console.log(error);
    }
    setIsLoading(false);
  }, [typeIds, fromDate, tillDate, rentalIds, composition, objects]);

  useEffect(() => {
    if (fromDate && tillDate) {
      getAvailableObjects();
    }
  }, [fromDate, tillDate]);
sage waveBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)