Created
October 16, 2019 07:37
-
-
Save ranyefet/28bd89b870ab0caec7f207dc70e9fdd5 to your computer and use it in GitHub Desktop.
Component Test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component} from "react"; | |
import axios from "axios"; | |
export class Login extends Component { | |
/** | |
* Submitting the form | |
*/ | |
submit() { | |
// creating a post request to log the user in | |
axios.post("http://localhost:3000/user/login?pass=" + this.refs.pass.value + "&user=" + this.refs.user.value).then(function (res) { | |
// if got a user in return, set the state | |
if (res.data.user) {this.setState({user: res.data.user})} | |
}); | |
} | |
/** | |
* Rendering the component | |
* @returns {*} | |
*/ | |
render() { | |
// fetching the user to check if he is logged in | |
axios.get("http://localhost:3000/user/current"). | |
then(function (res) { | |
this.setState({user: res.data.user}) | |
}); | |
// if the user is not logged in | |
if (!this.state.user) { | |
return <form onSubmit={this.submit}> | |
<input type="text" ref="user" name="email"/><br/><input type="text" ref="pass" name="pass"/><br/> | |
<button type="submit"/> | |
</form> | |
} | |
// if the user is logged in | |
if (this.state.user) { | |
// printing the user name Capitalized | |
var userName = this.state.user.name.toUpperCase(); | |
userName = userName[0].toLowerCase() + userName.substr(1); | |
return <h1>Welcome {userName}. Your role is {this.state.user.role}</h1> | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment