I decided that by contacting my Redux store from behind the Component tree and sending it the same action from the exit button, since my interceptors are created in a separate file and loaded before any component loads.
So basically, I did the following:
In the index.js file:
//....lots of imports ommited for brevity import { createStore, applyMiddleware } from 'redux'; import reduxThunk from 'redux-thunk'; import reducers from './reducers'; import { UNAUTH_USER } from './actions/types'; //this is just a constants file for action types. const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore); const store = createStoreWithMiddleware(reducers); //Here is the guy where I set up the interceptors! NetworkService.setupInterceptors(store); //lots of code ommited again... //Please pay attention to the "RequireAuth" below, we'll talk about it later ReactDOM.render( <Provider store={store}> <BrowserRouter> <div> <Header /> <main className="plan-container"> <Switch> <Route exact path="/" component={Landing} /> <Route exact path="/login" component={Login} /> <Route exact path="/signup" component={Signup} /> <Route exact path="/calendar" component={RequireAuth(Calendar)} /> <Route exact path="/profile" component={RequireAuth(Profile)} /> </Switch> </main> </div> </BrowserRouter> </Provider> , document.querySelector('.main-container'));
And in the network-service.js file:
import axios from 'axios'; import { UNAUTH_USER } from '../actions/types'; export default { setupInterceptors: (store) => { // Add a response interceptor axios.interceptors.response.use(function (response) { return response; }, function (error) { //catches if the session ended! if ( error.response.data.token.KEY == 'ERR_EXPIRED_TOKEN') { console.log("EXPIRED TOKEN!"); localStorage.clear(); store.dispatch({ type: UNAUTH_USER }); } return Promise.reject(error); }); } };
And last but not least, I have a HOC (higher order component) that I wrap with protected components, where I do the actual redirection when the session is absent. Thus, when I run the action type UNAUTH_USER, it sets my isLogged property in my session reducer to false , and therefore this component receives a notification and makes a redirect for me at any time.
File for require-auth.js :
import React, { Component } from 'react'; import { connect } from 'react-redux'; export default function(ComposedComponent) { class RequireAuth extends Component { componentWillMount() { if(!this.props.session.isLogged) { this.props.history.push('/login'); } }; componentWillUpdate(nextProps) { if(!nextProps.session.isLogged) { this.props.history.push('/login'); } }; render() { return <ComposedComponent {...this.props} /> } } function mapStateToProps(state) { return { session: state.session }; } return connect(mapStateToProps)(RequireAuth); }
Hope this helps!
source share