Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!