The type of application is web application, I get the code on the frontend, I send it to our backend on .net, there the backender exchanges the code for tokens and sends them to me on the frontend. Then I install them in the repository via setTokens, but after that the application redirects to portal and starts a new authorization. For some reason, oktaAuth does not update its state and removes tokens immediately from storage
import { useCallback, useEffect, useState } from “react”;
import { useHistory } from “react-router-dom”;
import { Box, CircularProgress } from “@mui/material”;
import { observer } from “mobx-react”;
import { useOktaAuth } from “@okta/okta-react”;
import { useRootStore } from “…/…/App”;
import { Tokens } from “@okta/okta-auth-js”;
const LoginCallback = observer(() => {
const history = useHistory();
const store = useRootStore();
const [tokens, setTokens] = useState();
const [tokensLoaded, setTokensLoaded] = useState(false);
const { oktaAuth, authState } = useOktaAuth();
// eslint-disable-next-line react-hooks/exhaustive-deps
const searchParams = new URLSearchParams(window.location.search);
const code = searchParams.get(“code”);
const codeVerifier = oktaAuth.transactionManager.storageManager
.getTransactionStorage()
.getItem(“codeVerifier”);
const getTokens = useCallback(
async (codeVerifier: string, code: string) => {
const res = await store.authStore.exchangeCode(code, codeVerifier);
setTokens(res);
},
[store.authStore],
);
useEffect(() => {
if (code && codeVerifier && !authState && !tokensLoaded) {
getTokens(codeVerifier, code);
}
}, [code, codeVerifier, authState, tokensLoaded]);
useEffect(() => {
if (!authState?.isAuthenticated && !tokensLoaded) {
if (tokens && !authState?.isAuthenticated && !tokensLoaded) {
oktaAuth.tokenManager.setTokens({
accessToken: tokens.accessToken,
idToken: tokens.idToken,
});
setTokensLoaded(true);
}
} else if (tokensLoaded && authState?.isAuthenticated) {
history.replace("/portal");
}
}, [authState, tokens]);