Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda