【问题标题】:Why are async api calls necessary with react-query?为什么 react-query 需要异步 api 调用?
【发布时间】:2022-01-20 02:31:00
【问题描述】:

每个文档都显示了异步调用与 react-query 一起使用,但我有点困惑为什么这些是必要的,因为以下代码在有或没有 async/await 的情况下都有效:

export const apiCall = (method, path, data) => {
    return axios({method, url: API_PREFIX + path, data})
        .then(resp => resp.data)
        .catch(error => {

        });
};

export const useData = () => {
    const {data, isLoading, error, refetch} = useQuery(
        'users',
        async () => await apiCall(dispatch, 'get', '/some-endpoint'),
    );

    return {
        userList: data,
        refetch,
        isLoading
    }
}

【问题讨论】:

  • 我不认为这是必要的,useQuery("users", () => apiCall(dispatch, "get", "/some-endpoint")); 这也应该有效,我认为这里唯一的期望是函数应该返回承诺。

标签: reactjs async-await react-query


【解决方案1】:

react-query 希望您返回已解决或已拒绝的承诺 - 您可以根据需要生成它。 JavaScript 有很多选项可以产生 Promise。 async / await 基本上只是与.then.catch 进行承诺链接的替代语法。

您发布的代码也可以,但是它也有一些不必要的部分:

async () => await apiCall(dispatch, 'get', '/some-endpoint'),

这里不需要 async / await,因为apiCall 已经返回了一个 Promise,所以这也是一样的:

() => apiCall(dispatch, 'get', '/some-endpoint'),

此外,我不会在 apiCall 函数中使用 .catch,因为它会将失败的 Promise 转换为成功的 Promise。使用 react-query,您真的希望将失败的 Promise 返回给 react-query,以便库可以为您进行错误处理。否则,它不知道错误并且不能重试/不能给你错误状态等。

所以对于apiCall,这两件事也是等价的,并且可以很好地与 react-query 配合使用:

export const apiCall = (method, path, data) => {
    return axios({method, url: API_PREFIX + path, data})
        .then(resp => resp.data)
};
export const apiCall = async (method, path, data) => {
    const response = await axios({method, url: API_PREFIX + path, data})
    return respons.data
};

这实际上取决于您更喜欢哪种语法 - 大多数人更喜欢 async / await 因为它避免了过多的回调链。

我也写了一篇关于这个主题的比较全面的博文:https://tkdodo.eu/blog/about-async-functions

【讨论】:

  • 谢谢,这太棒了。帮助我更好地理解。
【解决方案2】:

使用 React Query 简化异步数据

更多信息请访问https://tylerclark.dev/react-query/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-05
    • 2023-04-10
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多