Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

233
Vistas
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda