'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?



Solution 1:[1]

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])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 millhouse