Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Libraries
- import { connect } from 'react-redux'
- import React, { PureComponent, PropTypes } from 'react'
- // Our actions
- import { loginAction, redirectedToLoginAction } from 'store/actions'
- import './index.css'
- // Our components
- import { loginErrorToMessage } from '../../util'
- class Login extends PureComponent {
- constructor () {
- super()
- // Refs
- let { form, usernameInput, passwordInput } = this
- // Validation
- this.state = {
- emailInvalid: false,
- passwordInvalid: false
- }
- }
- static propTypes = {
- location: PropTypes.object.isRequired,
- hasBeenRedirected: PropTypes.func.isRequired,
- loginUser: PropTypes.func.isRequired,
- error: PropTypes.object,
- token: PropTypes.string
- }
- static contextTypes = {
- router: PropTypes.object.isRequired
- }
- componentDidMount () {
- if (this.props.location.state) {
- if (this.props.location.state.fromRegistration) {
- this.props.hasBeenRedirected()
- }
- }
- if (this.props.token) {
- setImmediate(this.context.router.push('/dashboard'))
- }
- }
- componentDidUpdate () {
- if (this.props.token) {
- setImmediate(this.context.router.push('/dashboard'))
- }
- }
- errorHandling = () => {
- !this.emailInput.value ? this.setState({usernameInvalid: true}) : this.setState({usernameInvalid: false})
- !this.passwordInput.value ? this.setState({passwordInvalid: true}) : this.setState({passwordInvalid: false})
- }
- handleClick = e => {
- e.preventDefault()
- // Check validity
- if (!this.form.checkValidity()) {
- this.errorHandling()
- return
- }
- // Set all input fields to valid
- this.setState({
- usernameInvalid: false,
- passwordInvalid: false
- })
- this.props.loginUser({
- email: this.emailInput.value,
- password: this.passwordInput.value
- })
- }
- render () {
- return (
- <form className='registerField' ref={f => { this.form = f }} >
- <label><strong>Login</strong> </label>
- <ul>
- <li>
- <label>Email:</label>
- <input
- type='text'
- name='email'
- placeholder='Email'
- ref={i => { this.emailInput = i }}
- required
- />
- </li>
- <li>
- <label>Password:</label>
- <input
- type='password'
- name='password'
- placeholder='Password'
- ref={i => { this.passwordInput = i }}
- />
- </li>
- </ul>
- <input type='submit' onClick={this.handleClick} />
- </form>
- )
- }
- }
- const mapStateToProps = state => ({
- token: state.getIn(['auth', 'token']),
- error: state.getIn(['auth', 'error'])
- })
- const mapDispatchToProps = (dispatch) => ({
- hasBeenRedirected: () => dispatch(redirectedToLoginAction()),
- loginUser: params => dispatch(loginAction(params))
- })
- export default connect(mapStateToProps, mapDispatchToProps)(Login)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement