Skip to content

Instantly share code, notes, and snippets.

@AshutoshSajan
Created January 24, 2020 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AshutoshSajan/26879fb0e24b2ad766f33297dd4e8049 to your computer and use it in GitHub Desktop.
Save AshutoshSajan/26879fb0e24b2ad766f33297dd4e8049 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import { Switch, Route, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import Login from './user/containers/Login';
import Register from './user/containers/Register';
import Header from './app/componets/Header';
import AdminDashboard from './admin/containers/AdminDashboard';
import UserDashboard from './user/containers/UserDashboard';
const BASE_URL = 'http://localhost:8000/api/v1';
class App extends Component {
state = {};
componentDidMount = () => {
const { jwt } = localStorage;
if (jwt) {
this.fetchData(BASE_URL + '/users/me', jwt);
} else if (!jwt) {
this.props.history.push('/users/login');
}
};
fetchData = (url, jwt) => {
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: jwt
}
})
.then(res => res.json())
.then(data => {
if (data && data.success) {
if (data.token) localStorage.setItem('jwt', data.token);
if (data.user) this.props.dispatch({ type: 'LOGIN', payload: data });
} else if (!data.success) {
this.props.history.push('/users/login');
}
})
.catch(err => {
console.log(err, 'auto login catch err');
});
};
handleLogout = () => {
localStorage.clear();
window.location.reload();
};
render() {
const { user } = this.props;
return (
<div className=''>
<Header user={user} handleLogout={this.handleLogout} />
<Switch>
<Route exact path='/users/login' component={Login} />
<Route path='/users/register' component={Register} />
</Switch>
{user && user.isAdmin ? (
<AdminDashboard />
) : user && !user.isAdmin ? (
<UserDashboard />
) : (
''
)}
</div>
);
}
}
function mapStateToProps(state) {
return state.user;
}
export default withRouter(connect(mapStateToProps)(App));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment