AllenYuan

auth - get token from localstorage

Apr 24th, 2020
621
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Child components
  2. import Header from './Header';
  3.  
  4. // modules for a redux-connected React component
  5. import React from 'react';
  6. import { connect } from 'react-redux';
  7. import agent from '../agent';
  8.  
  9. // extract appName from state
  10. const mapStateToProps = state => ({
  11.   appName: state.appName,
  12.   currentUser: state.common.currentUser,
  13.   redirectTo: state.common.redirectTo
  14. });
  15.  
  16. const mapDispatchToProps = dispatch => ({
  17.   onLoad: (payload, token) =>
  18.     dispatch({ type: 'APP_LOAD', payload, token }),
  19.   onRedirect: () =>
  20.     dispatch({ type: 'REDIRECT' })
  21. });
  22.  
  23. // render the appname
  24. class App extends React.Component {
  25.   componentWillMount() {
  26.     // get token from localstorage
  27.     const token = window.localStorage.getItem('jwt');
  28.     if (token) {
  29.       // pass it to agent
  30.       agent.setToken(token);
  31.     }
  32.     // add it to state
  33.     this.props.onLoad(token ? agent.Auth.current() : null, token);
  34.   }
  35.   // handle redirect if necessary
  36.   componentWillReceiveProps(nextProps) {
  37.     // need to redirect
  38.     if (nextProps.redirectTo) {
  39.       // redirect to given route
  40.       this.context.router.replace(nextProps.redirectTo);
  41.       // update redirectTo in state
  42.       this.props.onRedirect();
  43.     }
  44.   }
  45.  
  46.   render() {
  47.     return (
  48.       // render Header and children from router below that
  49.       <div>
  50.         <Header appName={this.props.appName} />
  51.         {this.props.children}
  52.       </div>
  53.     );
  54.   }
  55. }
  56.  
  57. // ensure react-router attaches children to this component's props
  58. App.contextTypes = {
  59.   router: React.PropTypes.object.isRequired
  60. };
  61.  
  62. // export redux-connected App
  63. export default connect(mapStateToProps, mapDispatchToProps)(App);
Advertisement
Add Comment
Please, Sign In to add comment