[英]How to use custom react query hook twice in the same component?
I have a custom hook like so for getting data using useQuery.我有一个自定义钩子,用于使用 useQuery 获取数据。 The hook works fine, no problem there.
钩子工作正常,没有问题。
const getData = async (url) => {
try{
return await axios(url)
} catch(error){
console.log(error.message)
}
}
export const useGetData = (url, onSuccess) => {
return useQuery('getData', () => getData(url), {onSuccess})
}
However, if I call this hook twice in my component it will only fetch data from the first call even with a different URL.但是,如果我在组件中调用此钩子两次,即使使用不同的 URL,它也只会从第一次调用中获取数据。 (Ignore the comments typo, that's intentional)
(忽略评论错字,这是故意的)
The call in my component:我的组件中的调用:
const { data: commentss, isLoading: commentsIsLoading } = useGetData(`/comments/${params.id}`)
const { data: forumPost, isLoading: forumPostIsLoading } = useGetData(`/forum_posts/${params.id}`)
When I console.log forumPost in this case, it is the array of comments and not the forum post even though I am passing in a different endpoint.在这种情况下,当我 console.log forumPost 时,它是评论数组而不是论坛帖子,即使我传递的是不同的端点。
How can I use this hook twice to get different data?我怎样才能使用这个钩子两次来获取不同的数据? Is it possible?
可能吗? I know I can just call parallel queries but I would like to use my hook if possible.
我知道我可以只调用并行查询,但如果可能的话,我想使用我的钩子。
Since useQuery
caches based on the queryKey
, use the URL in that name由于
useQuery
基于queryKey
缓存,因此在该名称中使用 URL
const getData = async(url) => { try { return await axios(url) } catch (error) { console.log(error.message) } } export const useGetData = (url, onSuccess) => { return useQuery('getData' + url, () => getData(url), { onSuccess }) } //........ const { data: commentss, isLoading: commentsIsLoading } = useGetData(`/comments/${params.id}`) const { data: forumPost, isLoading: forumPostIsLoading } = useGetData(`/forum_posts/${params.id}`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.