DEV Community

Cover image for User Login In React JS with OvermindJS
Aaron K Saunders
Aaron K Saunders

Posted on

User Login In React JS with OvermindJS

Simple authentication flow using OvermindJS and reactjs, using ionic framework components for the user interface. This the second part in a series of videos looking at how to use OvermindJS as an alternative state management library for your javascript projects.

This project is written using reactjs with typescript and Ionic Framework

Setting up the state was pretty straight forward except for ensuring the types are set appropriately.

export type IState = {
  error: any;
  currentUser: any;
  isLoggedIn: boolean;
};

const state: IState = {
  error: null,
  currentUser: null,
  // derived value
  isLoggedIn: derived<IState, boolean>(
    (state: IState) => state.currentUser != null
  ),
};

// state config
export const config = {
    state,
    actions
}

// hook to provide access in components
export const useApp = createHook<typeof config>();
Enter fullscreen mode Exit fullscreen mode

The authentication flow with protected routes is a fundamental basis for most applications. This example shows not only that flow, but the use of how to protect routes using the PrivateRoute function below.

export interface PrivateRouteProps extends RouteProps {
  component: any;
}

const PrivateRoute: React.SFC<PrivateRouteProps> = ({
  component: Component,
  ...props
}) => {
  const { state } = useApp();
  // use overmind to see if we have a user?
  let authUser = state.isLoggedIn;

  // if i have the login path, handle it differently...
  if (props.path === "/login") {
    return authUser ? <Redirect to="/" /> : <Route component={Login} />;
  }
  return (
    <Route
      {...props}
      render={(innerProps) => {
        return authUser ? (
          <Component {...innerProps} />
        ) : (
          <Redirect to="/login" />
        );
      }}
    />
  );
};
Enter fullscreen mode Exit fullscreen mode

And the application of that function in the setup of react-router in

const App: React.FC = () => (
  <IonApp>
    <IonReactRouter>
      <IonRouterOutlet>
        <Route path="/login" component={Login} exact={true} />
        <PrivateRoute path="/home" component={Home} exact={true} />
        <PrivateRoute
          path="/message/:id"
          component={ViewMessage}
          exact={true}
        />
        <Route exact path="/" render={() => <Redirect to="/home" />} />
      </IonRouterOutlet>
    </IonReactRouter>
  </IonApp>
);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)