Next.js Discord

Discord Forum

API fetch infinite loop

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
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]);

1 Reply

Birman
Fetch it in a server component in the page and pass it down to the component as a prop.