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

114
Vistas
Can not set state from graphql query until page refresh React/ GraphQL

I have a component which queries for a currently authed user via graphQl and useQuery hook

const Home = () => {
  const [state, setState] = useAppContext()
  const { data: authedUserData, error } = useQuery(GET_AUTHED_USER);

  console.log('authed user', authedUserData?.getAuthedUser) // logs authed user
  console.log('state', state) // logs null

  useEffect(() => {
    if (authedUserData?.getAuthedUser) {
      setState({
        ...state,
        currentUser: authedUserData.getAuthedUser,
        isAuthed: true
      });
    }
  }, [])


  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>

  return (
    <Posts data={data} header={<NavHeader />} />
  )
}

I am then trying to set whatever comes back from GET_AUTHED_USER into a piece of global state, I see in the logs authedUserData.getAuthedUser does log my user but state logs as null until I refresh the page. Placing any dependency inside the useEffect will trigger an infinite loop. How can I solve this?

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

0

Using an empty array as your useEffect dependency list tells React that you only want this function to be run once, after initial render. By the time your GraphQL result has come back, you've missed that.

You need to "listen" to the authedUserData, and act once it's no longer undefined:

 useEffect(() => {
    if (authedUserData?.getAuthedUser) {
      setState({
        ...state,
        currentUser: authedUserData.getAuthedUser,
        isAuthed: true
      });
    }
  }, [authedUserData])
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