Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react';
- import { findDOMNode } from "react-dom";
- import { connect } from 'react-redux';
- import { loginSuccess } from '../../actions/login';
- import { browserHistory } from 'react-router';
- import superagent from 'superagent';
- class LoginAndSignup extends Component {
- constructor(props) {
- super(props);
- let url = this.props.route.path === '/registro' ? 'api/users' : 'api/users/authorize'
- this.state = {
- waiting: false,
- ready: false,
- url
- };
- }
- doRequest(email, password) {
- superagent.post(this.state.url)
- .set('Accept', 'application/json')
- .send({
- user: {
- email: email,
- password: password
- }
- })
- .end((err, res) => {
- this.setState({ waiting: false });
- if (!err) {
- if (res.status === 200) {
- this.props.loginSuccess(res.body.token, res.body.user);
- }
- }
- });
- }
- isReadyToSubmit() {
- let email = this.refs.emailInput.value;
- let password = this.refs.passwordInput.value;
- let ready = email.trim() && password.trim() ? true : false;
- this.setState({ready});
- }
- onSubmit(e) {
- e && e.preventDefault();
- this.doRequest(this.refs.emailInput.value, this.refs.passwordInput.value);
- this.setState({waiting: true});
- }
- shouldComponentUpdate(nextProps) {
- console.log(nextProps);
- if (nextProps.token) {
- console.log('token');
- browserHistory.push('/dashboard');
- return false;
- }
- return true;
- }
- render() {
- let disabled = !!this.state.waiting || !!!this.state.ready;
- if (true) return (
- <form onSubmit={::this.onSubmit}>
- <div>
- <input type="email" placeholder="E-mail" ref="emailInput" onChange={::this.isReadyToSubmit}></input>
- </div>
- <div>
- <input type="password" placeholder="Contraseña" ref="passwordInput" onChange={::this.isReadyToSubmit}></input>
- </div>
- <div>
- <button disabled={disabled} type="submit">{this.props.route.path === '/registro' ? 'Regístrate' : 'Accede'}</button>
- </div>
- </form>
- );
- }
- }
- export default connect(
- state => {
- return {
- session: state.session
- }
- },
- {
- loginSuccess
- }
- )(LoginAndSignup);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement