0

I have a parent component that always needs to retrieve a token first before the subcomponents get executed. As discussed in this post What is the correct order of execution of useEffect in React parent and child components? the subcomponents useEffect gets executed first.

My question is how can I handle retrieving the token on initial loading (in the main component)?

Grifting
  • 57
  • 1
  • 9

1 Answers1

0

I solved it by using a state to track if the session has been initialized. If the session has not been initialized its displaying a loading animation. This is only executed on the initial loading of the app. The loading component can't have a useEffect that requires the api with a valid token or user information.

function App() {
  const [hasSession, setSession] = useState(false)

  useEffect(() => {
    async function initUserProfile() {
      await apiService.init()
      setSession(true)
    }

    initUserProfile()
  }, [])

  if (hasSession === false) {
    return (<Loading />)
  }

  return (
    <Router>...</Router>
  )
 }
Grifting
  • 57
  • 1
  • 9