Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var React = require('react')
- var loginPage = React.createClass({
- getInitialState: function () {
- return {
- token: null,
- user: null,
- badLogin: null
- }
- },
- submitCredentials: function (user) {
- if (user.username !== undefined && user.password !== undefined) {
- this.login({
- username: user.username,
- password: user.password
- }, () => {
- this.setState({ badLogin: true });
- })
- }
- },
- login: function (user, callback) {
- fetch(API_URL, {
- method: 'POST',
- headers: {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(user)
- }).then((response) => {
- return response.json()
- }).then((response) => {
- if (response.token && response.user) {
- localStorage.setItem(('login', JSON.stringify([{'token': response.token}, {'userId': response.user.id}]))
- } else {
- if (callback) { callback() }
- }
- }).done()
- },
- componentWillMount: function () {
- var token;
- var data = JSON.parse(localStorage.getItem('login'))
- if (data[0]) {
- token = data[0]
- this.getUser(data[1])
- .then((user) => {
- return user
- })
- .then((user) => {
- this.setState({
- user: user,
- token: token
- })
- })
- }
- },
- getUser: function (userId) {
- return fetch(PROFILE_URL + userId, {
- method: 'GET',
- headers: {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json'
- }
- })
- },
- logout: function () {
- fetch(LOGOUT_URL, {
- method: 'GET'
- }).then(function () {
- localStorage.removeItem('login')
- })
- },
- render: function () {
- if (!this.state.token) {
- return (
- <MyForm />
- )
- } else {
- return (
- <Profile />
- );
- }
- }
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement