search

Home  >  Q&A  >  body text

React Query's .isSuccess error occurs when I use axios to make a get request

<p><br /></p> <pre class="brush:php;toolbar:false;">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("搜索结果为空"); } setFetchedInvoiceData(fetchInvoices.data); } if (fetchInvoices.isError) { console.log(fetchInvoices.error); }</pre> <p>我有一个按钮,有一个onClick事件,调用fetchInvoices.refetch()时出现错误。第一个错误是“重新渲染次数过多。React限制了渲染次数以防止无限循环。”如果我去掉<code>setFetchedInvoiceData(fetchInvoices.data);</code>并且数组返回为0,它会触发我的react-hot-toast函数<code>toast.error("搜索结果为空");</code>但然后我会收到警告“在渲染不同组件(<code>App</code>)时无法更新组件(<code>Ie</code>)”。我做错了什么,如何修复这个问题?</p>
P粉153503989P粉153503989455 days ago451

reply all(1)I'll reply

  • P粉517090748

    P粉5170907482023-08-16 18:54:18

    It's hard to give you the best solution without looking at your entire component's code, but currently here I see that you are getting fetchInvoices.isSuccess on every re-render Running condition, the best way to solve it is to add it to useEffect like this:

    useEffect(() => {
          if (fetchInvoices.isSuccess) {
            if (fetchInvoices.data.length === 0) {
              toast.error("搜索结果为空");
            }
            setFetchedInvoiceData(fetchInvoices.data);
          }
         if (fetchInvoices.isError) {
           console.log(fetchInvoices.error);
         }
       }, [fetchInvoices.isSuccess, fetchInvoices.isError])

    reply
    0
  • Cancelreply