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

Time:12-08

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.

CodePudding user response:

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}`)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related