0

I am trying out react and building a login form for a one page application using the same. I am using redux to store the user's information throughout the application and still cant get past through the boilerplate setup for the same.

I am almost done, but I cannot dispatch my action using the dispatch method, here is the code for my login component:

    import React, { Component } from 'react'
import { NavLink } from 'react-router-dom'
import { connect } from 'react-redux';

// import user actions

import { logMeIn } from "../actions/userActions"

const boxStyle = {
    width: "400px",
    margin: "40px auto",
}



export default connect((store)=>{
    return {
        user: store.user
    };
})(class loginBox extends Component {

    login() {
        let email = document.getElementById("email");
        let password = document.getElementById("password");
        email = email.value;
        password = password.value;

        return this.props.dispatch(logMeIn(email, password))
    }

    render(){
        return (
            <div className="box" style={boxStyle}>
              <form className="form">
                <div className="field">
                    <label className="label">Your Email</label>
                    <input className="input" type="email" id="email" />
                </div>
                <div className="field">
                    <label className="label">Your Password</label>
                    <input className="input" type="password" id="password" />
                </div>
                <div className="level">
                    <button className="button is-dark" type="button" onClick={ this.login }>Login</button>
                    <NavLink to="/">Reset password</NavLink>
                </div>
              </form>
            </div>
          )
        }
})

here, The code is compiled without any errors, and the login page is displayed, BUT when the form is submitted, following error occurs:

× TypeError: Cannot read property 'props' of undefined

pointing to return this.props.dispatch(logMeIn(email, password)) line in the code.

As being new to redux, I am not able to fully understand it, however, have a look at my store:

    import { createStore, applyMiddleware } from 'redux';
import reducer from './reducers'
import logger from 'redux-logger'
import thunk from 'redux-thunk'

const middleware = applyMiddleware(logger, thunk)

export default createStore(reducer, middleware)

it is simple. I am definitely missing on something here, and I do not know what it is.. please help me resolve this issue.

Thanks

sameer manek
  • 735
  • 1
  • 11
  • 34

1 Answers1

0

This is a special case of this popular problem. It isn't related to Redux. login method is used as a callback, and loses this context.

It should be either:

login = this.login.bind(this);

login() {...}

Or:

login = () => {...}

The former is preferable for several reasons.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565