frontend/smart-hut/src/App.js

110 lines
2.4 KiB
JavaScript

import React from "react";
import { Switch, Route, Redirect } from "react-router-dom";
import Home from "./views/Home";
import Dashboard from "./views/DashboardTest";
import Signup from "./views/Signup";
import Login from "./views/Login";
import { call } from './client_server';
/*const ProtectedRoute = ({ component: Comp, loggedIn, logOut, path, ...rest }) => {
return (
<Route
path={path}
{...rest}
render={(props) => {
return loggedIn ? (
<Comp logOut={logOut} {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: {
prevLocation: path,
error: "You need to login first!",
},
}}
/>
);
}}
/>
);
};*/
class App extends React.Component {
constructor(props) {
super(props);
let loggedIn = false;
try {
let userJsonString = localStorage.getItem("token");
if (userJsonString) {
loggedIn = true;
}
} catch (exception) {
}
this.state = {
loggedIn: loggedIn,
};
this.auth = this.auth.bind(this);
this.logout = this.logout.bind(this);
}
auth(data) {
return call.login(data.params)
.then(res => {
console.log(res);
if (res.data && res.status === 200) {
this.setState(
{
user: data.params.user,
token: res.data.jwttoken,
loggedIn: true,
}
);
localStorage.setItem("token", JSON.stringify(res.data.jwttoken));
this.props.history.push("/dashboard");
} else {
this.setState({
error: res.data.message
});
}
}).catch(err => {
console.log(err);
});
};
logout() {
this.setState({
loggedIn : false,
});
localStorage.removeItem("token");
this.props.history.push("/");
};
render() {
return (
<Switch>
<Route path="/" exact component={Home} />
<Route path="/login" >
{this.state.loggedIn ? <Redirect to="/dashboard" /> : <Login auth={this.auth} />}
</Route>
<Route path="/signup" exact component={Signup} />
<Route path="/dashboard" >
{this.state.loggedIn ? <Dashboard logout={this.logout} /> : <Redirect to="/login" />}
</Route>
</Switch>
);
}
}
export default App;