• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

196
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.

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

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda