Untitled

 avatar
unknown
javascript
3 years ago
1.6 kB
7
Indexable

const Router = () => {
  const { isAuthenticated } = useContext(AuthContext)

  return isAuthenticated ? (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<RedirectPage />} />
      </Routes>
    </BrowserRouter>
  ) : (
    <BrowserRouter>
      <Routes>
        <Route path="/callback" element={<AuthenticationCallback />} />
        <Route path="/error" element={<ErrorPage />} />
        <Route path="*" element={<Authentication />} /> // Flow starts here
      </Routes>
    </BrowserRouter>
  )
}


const Authentication = () => {
  const { initAuthentication, isAuthenticated } = useContext(AuthContext)

  if (!isAuthenticated) {
    initAuthentication() // calls function within AuthProvider.js which starts the Spotify flow and redirects to /callback (which opens <AuthenticationCallback />)
  }
}

const AuthenticationCallback = () => {
  const [params] = useSearchParams()
  const { isAuthenticatedHandler } = useContext(AuthContext)

  const login = () => {
    if (params.has('code') && params.has('state')) {
      isAuthenticatedHandler(params.get('code'), params.get('state')) // Persist the urlParams within the AuthenticationProvider
    }

    useNavigate('/')
  }

  login()

  return <div>AuthenticationCallback</div>
}

// inside AuthContext.js, within `const AuthProvider = ({ children }) => {...}`
const isAuthenticatedHandler = (codeParam, stateParam) => {
  setCode(codeParam) // This setState()-call is the culprit and causes the exception, because it is called from `AuthenticationCallback` which is still rendering
  setStateIdentifier(stateParam)
  setIsAuthenticated(true)
}
Editor is loading...