DEV Community

Aaron K Saunders
Aaron K Saunders

Posted on

Learn to Build Mobile Apps With Ionic Framework, ReactJS and Capacitor: Manage Authentication State using React Context API

Learn to Build Mobile Apps With Ionic Framework, ReactJS and Capacitor : Manage Authentication State using React Context API

Alt Text

Overview

We modify the Ionic Framework ReactJS Two Tab Application from the previous lesson to now have a LoginPage Component.

The LoginPage Component is setup in a separate navigation stack than the navigation stack that supports the Two Tabs. I find this is an easier approach than wrapping each route with a protected function and it just is simpler to visually see what is happening in the application when reading the code.

The application changes the default Navigation Stack using IonicRouter from the Ionic implementation of React Navigation when the authentication state changes. The authentication state in managed in the new context component that we build in this video

const App: React.FC = () => {
  const { authValue } = React.useContext(AuthContext);

  return (
    <IonApp>
      {!authValue.authenticated ? (
        <IonReactRouter>
          <Route path="/login" component={LoginPage} exact={true} />
          <Route
            path="/"
            render={() => <Redirect to="/login" />}
            exact={true}
          />
          <Route
            path="*"
            render={() => <Redirect to="/login" />}
            exact={true}
          />
        </IonReactRouter>
      ) : (
        <IonReactRouter>
          <IonTabs>
            <IonRouterOutlet>
              {/* specify route to each of teh tabs*/}
              <Route path="/tab1" component={Tab1} exact={true} />
              <Route path="/tab2" component={Tab2} exact={true} />
              <Route
                path="/tab2/tab-detail"
                component={TabDetail}
                exact={true}
              />
              {/* default route is to tab1 */}
              <Route
                path="/"
                render={() => <Redirect to="/tab1" />}
                exact={true}
              />
            </IonRouterOutlet>
            {/* draw what the tab bar should look like*/}
            <IonTabBar slot="bottom">
              <IonTabButton tab={"tab1"} href={"/tab1"}>
                <IonLabel>{"Tab One"}</IonLabel>
              </IonTabButton>
              <IonTabButton tab={"tab2"} href={"/tab2"}>
                <IonLabel>{"Tab Two"}</IonLabel>
              </IonTabButton>
            </IonTabBar>
          </IonTabs>
        </IonReactRouter>
      )}
    </IonApp>
  );
};
Enter fullscreen mode Exit fullscreen mode

We rename the context that we created to AuthContext and we add the authValues and expose functions to login and logout of the application.

Then in the application we access the context values for authentication status, authenticated and we use the functions when we want to login or logout.

export const AuthProvider: React.FC = ({ children }) => {
  // the reactive values
  const [authValues, setAuthValues] = React.useState<any>({
    authenticated: false,
    user: null,
  });

  const login = ({ user, password }: { user: string; password: string }) => {
    return new Promise((resolve) => {
      if (user === "aaron" && password === "aaron") {
        setAuthValues({
          authenticated: true,
          user: { user: user, id: "aaron-100" },
        });
        resolve(true);
      } else {
        resolve(false);
      }
    });
  };

  const logout = () => {
    setAuthValues({
      authenticated: false,
      user: null,
    });
    return Promise.resolve(true);
  };

  // the store object
  let state = {
    authValues,
    login,
    logout,
  };

  // wrap the application in the provider with the initialized context
  return <Context.Provider value={state}>{children}</Context.Provider>;
};
Enter fullscreen mode Exit fullscreen mode

The Video

Other Videos In The Series

Part One : Here we start with the famous two tab application and walk through the structure of the application how to set up the routes for the tabs also how you implement a detail screen for a specific tab.
[VIDEO] https://youtu.be/LGyqrZ85RDk

Part Two: Managing State Between Two Tabs using ReactJS Context API: we just walkthrough a simple solution where we change the value in one tab and use the context api to manage the value, and provide access to the value in different tabs in the application.
[VIDEO] https://youtu.be/DiCzp5kIcP4

Important Links

React Documentation Referenced

Latest comments (2)

Collapse
 
aaronksaunders profile image
Aaron K Saunders

i try to keep it going!! Thanks for taking the time to leave a comment

Collapse
 
jegangits profile image
jegan

.,,mmm