简体   繁体   中英

How to use custom react query hook twice in the same component?

I have a custom hook like so for getting data using 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. (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.

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

 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}`)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM