how to conditionally call a RTK-query hook in a loop though we cant use it inside useEffect

huangapple go评论74阅读模式
英文:

how to conditionally call a RTK-query hook in a loop though we cant use it inside useEffect

问题

useEffect(() => {
  const fetchServiceProducts = async () => {
    if (isSuccess === true && data) {
      for (let i = 0; i < data?.data.length; i++) {
        const serviceid = data.data[i].service_id;
        console.log(serviceid, "serviceid");
        const { data: serviceProduct } = await useServicedataByidQuery(serviceid).refetch();
        console.log(serviceProduct, "serviceata");
      }
    }
  };
  fetchServiceProducts();
}, []);

由于无法在回调中添加 RTKQ 钩子,您如何使这个可能,并在循环长度完成后调用我的查询并获取收集的数据?

英文:
useEffect(() =&gt; {
  const fetchServiceProducts = async () =&gt; {
    if (isSuccess === true &amp;&amp; data) {
      for (let i = 0; i &lt; data?.data.length; i++) {
        const serviceid = data.data[i].service_id;
        console.log(serviceid, &quot;serviceid&quot;);
        const { data: serviceProduct } = await useServicedataByidQuery(serviceid).refetch();
        console.log(serviceProduct, &quot;serviceata&quot;);
      }
    }
  };
  fetchServiceProducts();
}, []);

As we can't add RTKQ hook inside a callback, how do I make this possible and call my query after the loop length is completed and get collected data?

答案1

得分: 1

你可能想使用查询的“懒惰”版本。这会返回一个可以随时调用的“触发器”函数。更多详情请参阅useLazyQuery

示例:

const [trigger] = useLazyServicedataByidQuery(/* 查询选项 */);

useEffect(() => {
  const fetchServiceProducts = async () => {
    if (isSuccess && data) {
      for (let i = 0; i < data?.data.length; i++) {
        const serviceId = data.data[i].service_id;
        console.log({ serviceId });

        const { data: serviceProduct } = await trigger(serviceId);
        console.log({ serviceProduct });
      }
    }
  };

  fetchServiceProducts();
}, []);
英文:

You likely want to be using the "lazy" version of the query. This returns a "trigger" function that can be called at-will. See useLazyQuery for more details.

Example:

const [trigger] = useLazyServicedataByidQuery(/* query options */);

useEffect(() =&gt; {
  const fetchServiceProducts = async () =&gt; {
    if (isSuccess &amp;&amp; data) {
      for (let i = 0; i &lt; data?.data.length; i++) {
        const serviceId = data.data[i].service_id;
        console.log({ serviceId });

        const { data: serviceProduct } = await trigger(serviceId);
        console.log({ serviceProduct });
      }
    }
  };

  fetchServiceProducts();
}, []);

huangapple
  • 本文由 发表于 2023年5月25日 18:55:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定