javascriptreactjsreact-reduxoktaokta-api

How to stop page refresh after okta token refresh after every 2 min


import React from "react";
import { Route, Redirect, Switch } from "react-router-dom";
import { useOktaAuth } from "@okta/okta-react";
import { Superadmin } from "../../../../Application_Constants";
import { AuthPage } from "./AuthPage";
import { ErrorPage1 } from "../../errors/ErrorPage1";
import { makeStyles, useTheme } from "@material-ui/core/";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducer from "../../redux/reducer";
import Header from "../../header/Header";

const AppWithRouterAccess = () => {
  const store = createStore(reducer, applyMiddleware(thunk));

  const theme = useTheme();
  const { authState, oktaAuth } = useOktaAuth();

  return (
    <Switch>
      {!authState.isAuthenticated ? (
        /*Render auth page when user at `/auth` and not authorized.*/

        <Route>
          <AuthPage />
        </Route>
      ) : (
        /*Otherwise redirect to root page (`/`)*/
        <Redirect from="/auth" to="/" />
      )}

      <Route path="/error" component={ErrorPage1} />

      {!authState.isAuthenticated ? (
        /*Redirect to `/auth` when user is not authorized*/
        <Redirect to="/auth/login" />
      ) : (
        <>
          {/* provider used to integrates redux store with react application */}
          {/* redux provides a centralized store to manage the state of application */}
          <Provider store={store}>
            <Header />
          </Provider>
        </>
      )}
    </Switch>
  );
};

export default AppWithRouterAccess;

This is AppWithRouterAccess.js file. authState.isAuthenticated is getting refresh because Okta token refreshes and my page is getting refreshed and store refreshes. How can I stop my Redux to get refreshed after authState.isAuthenticated updates. Redux store should not get updated.


Solution

  • The store is recreated each time AppWithRouterAccess renders for any reason. Create the store outside the component so it's instantiated only once.

    const store = createStore(reducer, applyMiddleware(thunk));
    
    const AppWithRouterAccess = () => {
      const theme = useTheme();
      const { authState, oktaAuth } = useOktaAuth();
    
      return (
        <Provider store={store}>
          <Switch>
            {!authState.isAuthenticated ? (
              <Route>
                <AuthPage />
              </Route>
            ) : <Redirect from="/auth" to="/" />
            }
    
            <Route path="/error" component={ErrorPage1} />
    
            {!authState.isAuthenticated
              ? <Redirect to="/auth/login" />
              : <Header />
            }
          </Switch>
        </Provider>
      );
    };