React查询:如何在单击按钮时使用Query

bcs8qyzn  于 2022-12-14  发布在  React
关注(0)|答案(8)|浏览(291)

我是这个react-query库的新手。
我知道,当我想获取数据时,我可以使用这个库执行如下操作:

const fetchData = async()=>{...}

// it starts fetching data from backend with this line of code
const {status, data, error} = useQuery(myKey, fetchData());

它工作。但如何触发数据获取只有当一个按钮被点击?,我知道我可能会做一些像<Button onPress={() => {useQuery(myKey, fetchData())}}/>,但如何管理返回的数据和状态...

qxsslcnc

qxsslcnc1#

根据API Reference,您需要将enabled选项更改为false,以禁止自动运行查询。然后手动重新获取。

// emulates a fetch (useQuery expects a Promise)
const emulateFetch = _ => {
  return new Promise(resolve => {
    resolve([{ data: "ok" }]);
  });
};

const handleClick = () => {
  // manually refetch
  refetch();
};

const { data, refetch } = useQuery("my_key", emulateFetch, {
  refetchOnWindowFocus: false,
  enabled: false // disable this query from automatically running
});

return (
  <div>
    <button onClick={handleClick}>Click me</button>
    {JSON.stringify(data)}
  </div>
);

工作沙盒here
额外的好处:你可以将任何返回布尔值的东西传递给enabled。这样你就可以创建Dependant/Serial查询了。

// Get the user
const { data: user } = useQuery(['user', email], getUserByEmail)
 
// Then get the user's projects
const { isIdle, data: projects } = useQuery(
  ['projects', user.id],
  getProjectsByUser,
  {
    // `user` would be `null` at first (falsy),
    // so the query will not execute until the user exists
    enabled: user,
  }
)
gmol1639

gmol16392#

你必须传递manual: true参数选项,这样查询在装载时就不会获取。另外,你应该传递fetchData而不带括号,这样你就传递了函数引用而不是值。要调用查询,你可以使用refetch()。

const {status, data, error, refetch} = useQuery(myKey, fetchData, {
      manual: true,
    });

const onClick = () => { refetch() }

有关更多信息,请参阅react-query文档中的手动查询部分https://github.com/tannerlinsley/react-query#manual-querying

yiytaume

yiytaume3#

看起来文档更改了,现在缺少了手动查询部分。但是查看useQuery API,您可能需要将enabled设置为false,然后在按下按钮时使用refetch手动查询。您还可能需要使用force: true使其查询而不考虑数据新鲜度。

rnmwe5a2

rnmwe5a24#

您可以尝试此版本:

const fetchData = async()=>{...}

// it starts fetching data from backend with this line of code
const {status, data, error, refetch } = useQuery(
myKey, 
fetchData(),
{
  enabled: false,
}
);
const onClick = () => { refetch() }
// then use onClick where you need it

来自文档Doc
enabled: boolean

  • 将此项设置为false可禁止此查询自动运行。
  • 可用于相关查询。

refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>

  • 手动重取查询的函数。
  • 如果查询出错,则只记录错误。如果希望引发错误,请传递throwOnError: true option
  • 如果cancelRefetchtrue,则在做出新请求之前,将取消当前请求
vwhgwdsa

vwhgwdsa5#

如果要触发多次重新获取,还有另一种方法可以实现此目的。

const [fetch, setFetch] = useState(null);
const query = useQuery(["endpoint", fetch], fetchData);

const refetch = () => setFetch(Date.now());

// call the refetch when handling click.

如果要重新获取多个实体,则可以有一个顶级useState,它被称为fetchAll示例,并且:

...
const query = useQuery(["endpoint", fetch, fetchAll], fetchData);
...

并且如果您按下按钮获取所有内容,也会触发此代码。

gajydyqb

gajydyqb6#

首先,响应查询会提供启用选项,默认情况下为true

const fetchData = async()=>{...}

const {status, data, error , refetch} = useQuery(myKey, fetchData() , {
enabled : false
}
);

<button onClick={() => refetch()}>Refetch</button>
cwdobuhd

cwdobuhd7#

如果键相同,则使用refetch(),如果键不同,则使用useState触发查询。
例如:

const [productId, setProductId] = useState<string>('')
const {status, data, error, refetch} = useQuery(productId, fetchData, {
      enable: !!productId,
    });

const onClick = (id) => { 
if(productId === id) {
  refetch() 
}
else {
 setProductId(id)
}

}
yxyvkwin

yxyvkwin8#

您可以使用useLazyQuery()

import React from 'react';
import { useLazyQuery } from '@apollo/client';

function DelayedQuery() {
   const [getDog, { loading, error, data }] = useLazyQuery(GET_DOG_PHOTO);

   if (loading) return <p>Loading ...</p>;
   if (error) return `Error! ${error}`;

   return (
      <div>
         {data?.dog && <img src={data.dog.displayImage} />}
         <button onClick={() => getDog({ variables: { breed: 'bulldog' } })}>Click me!</button>
      </div>
   );
}

参考:https://www.apollographql.com/docs/react/data/queries/#manual-execution-with-uselazyquery

相关问题