0
const searchInvoiceList = async (
  plantLoc: string,
  invoiceOption: string
) => {
  let data: InvoiceData[] = [];
  await axios
    .get(`${linkURL}inv/getControlList/${plantLoc}/${invoiceOption}`)
    .then((response) => {
      data = response.data.sqlData;
    })
    .catch((error) => console.error(error));
  return data;
};

  const fetchInvoices = useQuery({
    queryKey: [
      "invoiceData",
      plantLocationOptionChecked.value,
      invoiceOptionChecked.value,
    ],
    queryFn: () =>
      searchInvoiceList(
        plantLocationOptionChecked.value,
        invoiceOptionChecked.value
      ),
    enabled: false,
    retry: 0,
  });
  if (fetchInvoices.isSuccess) {
    if (fetchInvoices.data.length === 0) {
      toast.error("Search Results were empty");
    }
    setFetchedInvoiceData(fetchInvoices.data);
  }
  if (fetchInvoices.isError) {
    console.log(fetchInvoices.error);
  }

I have a button that has an onClick and calls fetchInvoices.refetch() I get errors. The first error is "to many re-renders. React limits the number of renders to prevent an infinite loop.". If I get rid of setFetchedInvoiceData(fetchInvoices.data); and the array returns is 0, it triggers my react-hot-toast function toast.error("Search Results were empty"); but then I get the warning "cannot update a component (Ie) while rendering a different component (App)". What am I doing wrong and how can I fix this?

Zach philipp
  • 125
  • 6

1 Answers1

1

hard to give you the best solution without looking at the code of your whole component, but so far, in here I see that you're running the condition on fetchInvoices.isSuccess in every re-render, the best way to solve it is add it inside a useEffect, like this:

    useEffect(() => {
      if (fetchInvoices.isSuccess) {
        if (fetchInvoices.data.length === 0) {
          toast.error("Search Results were empty");
        }
        setFetchedInvoiceData(fetchInvoices.data);
      }
     if (fetchInvoices.isError) {
       console.log(fetchInvoices.error);
     }
   }, [fetchInvoices.isSuccess, fetchInvoices.isError])
Eduardo Palacio
  • 301
  • 1
  • 10