Accessing Redux Store from routes set up via React Router

Viewed 16218

I would like to make use of react-router's onEnter handler in order to prompt users to authenticate when entering a restricted route.

So far my routes.js file looks something like this:

import React from 'react';
import { Route, IndexRoute } from 'react-router';

export default (
    <Route   path="/"         component={App}>
      <IndexRoute             component={Landing} />
      <Route path="learn"     component={Learn} />
      <Route path="about"     component={About} />
      <Route path="downloads" component={Downloads} onEnter={requireAuth} />
    </Route>
)

Ideally, I'd like my requireAuth function to be a redux action that has access to the store and current state, that works like this: store.dispatch(requireAuth()).

Unfortunately I don't have access to the store in this file. I don't think I can use really use connect in this case to access the relevant actions that I want. I also can't just import store from the file where the store is created, as this is undefined when the app first loads.

4 Answers

After trying out a few of the above suggestions, I found the best way to track the state of your store with updates is to use React-Redux's useSelector function which basically connects a functional component to the store.

import * as React from "react";
import {Redirect, Route, Switch} from "react-router";
import {Provider, useSelector} from "react-redux";
import { createBrowserHistory } from "history";

// Your imports
import {IApplicationState,} from "./store/store";
import {Login} from "./routes/login/login.component";
import {getToken} from "./store/helpers/httpHelpers";


function handleRedirect() {
    if(!getToken()) {
        return <Redirect to="/login"/>;
    }
}

const restricted = (Component: _ComponentType, isLoggedIn: boolean) => {
   // Don't redirect here if there is a token in localStorage.
   // This is happening when we are on a restricted route and the user
   // refreshes & the isLoggedIn state hasn't been updated yet.
    return !isLoggedIn ? (
        () => handleRedirect()
    ) : () => <Route component={Component}/>
};

const AuthenticateRoutes = () => {
    const isLoggedIn = useSelector((state: IApplicationState) => state.auth.isLoggedIn);
    return (
        <Switch>
            <Route path="/login" component={Login} />
            <Route path="/downloads" render={restricted(Download, isLoggedIn)} />
        </Switch>
    );
};

export function App() {
    return (
        <Provider store={store}>
            <>
                <Router history={createBrowserHistory()}>
                    <AuthenticateRoutes />
                </Router>
            </>
        </Provider>
    );
}
Related