Home  >  Q&A  >  body text

How to pass parameters to function in React Query's useQuery function when enabled is set to false?

<p>I am creating a query that allows me to copy a template. The query to copy the template requires an id, but initially there isn't any. How can I pass the id as parameter to the query function when I call it in the onClick function. </p> <p>Function to copy template:</p> <pre class="brush:php;toolbar:false;">duplicate: ({ queryKey: [_key, id] }) => axios.get(`${base_url}templates/${id}/duplicate ?auth_token=${auth_token}`),</pre> <p>My query:</p> <pre class="brush:php;toolbar:false;">const { data: duplicateTemplate, refetch: duplicateTemplateFunc } = useQuery( [`template], api.duplicate, { enabled: false, onSuccess: () => { message.success('Template copied successfully.') }, } )</pre> The <p>onClick method is used in the render method of the antd table, and gives me the id through <code>record.id</code>. </p> <pre class="brush:php;toolbar:false;">render: (_value, record) => ( <div onClick={() => duplicateTemplateFunc(record.id)> copy </div> ),</pre>
P粉493313067P粉493313067443 days ago539

reply all(1)I'll reply

  • P粉675258598

    P粉6752585982023-08-27 14:57:52

    当使用react-query库中的useQuery hook并将enabled设置为false时,您仍然可以将参数传递给正在执行的函数。您只需要将参数作为对象传递给useQuery hook的第二个参数。
    const { data, isLoading, error } = useQuery(
    ["fetchData", { id: 123, name: "John" }],
    (_key, params) => {
    return fetch(`https://your-api.com/data/${params.id}?name=${params.name}`)
      .then(res => res.json());
    },
    { enabled: false }
    );

    reply
    0
  • Cancelreply