Learn to Build Mobile Apps With Ionic Framework, ReactJS and Capacitor: Manage Authentication State using React Context API
Tags: react, ionic, webdev, tutorial
Published: 2020-05-29 15:29:51

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/72m8ef5d1bdv6p3ewwfs.jpg)

###Overview

We modify the [Ionic Framework ReactJS](https://ionicframework.com/docs/react) 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](https://ionicframework.com/docs/react/navigation) when the authentication state changes. The authentication state in managed in the new context component that we build in this video

```react
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>
  );
};
```

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.

```react
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>;
};
```



###The Video
{% youtube 9yVQfuYSWOE %}

###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
- Ionic ReactJS Playlist [View Videos](
https://www.youtube.com/playlist?list=PL2PY2-9rsgl3OHIMYb1AzVG5wADUxOmUW)

React Documentation Referenced
- https://reactjs.org/docs/hooks-reference.html#usecontext
- https://reactjs.org/docs/context.html#when-to-use-context