Reputation: 51
TypeError: Cannot read property 'isAuthenticated' of undefined Function.mapStateToProps [as mapToProps] E:/smnd/client/src/components/auth/Login.js:69
function mapStateToProps (state){
return{
isAuthenticated: state.auth.isAuthenticated
}
}
this is the code of Login.js
import React, {Fragment, useState } from 'react';
import {Link, Redirect} from 'react-router-dom';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import {login} from '../../actions/auth';
// import {isAuthenticated} from '../../reducers/auth';
const Login = ({login, isAuthenticated}) => {
const [formData, setFormData] = useState({
email: '',
password: ''
});
const { email, password} = formData;
const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value });
const onSubmit = async e => {
e.preventDefault();
login(email,password);
};
// redirected if logged in
if (isAuthenticated) {
return <Redirect to='/dashboard' />;
}
return (
<Fragment>
<h1 className="large text-primary">Sign In</h1>
<p className="lead"><i className="fas fa-user"></i> Sign Into Your Account</p>
<form className="form" onSubmit={e => onSubmit(e)}>
<div className="form-group">
<input type="email" placeholder="Email Address" name="email" value={email} onChange={ e => onChange(e)} />
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
name="password"
value={password}
onChange={ e => onChange(e)}
/>
</div>
<input type="submit" className="btn btn-primary" value="Login" />
</form>
<p className="my-1">
Don't have an account? <Link to="/register">Sign Up</Link>
</p>
</Fragment>
);
};
Login.propTypes = {
login: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool
}
// const mapStateToProps = state => ({
// isAuthenticated: state.auth.isAuthenticated
// });
function mapStateToProps (state){
return{
isAuthenticated: state.auth.isAuthenticated
}
}
export default connect(mapStateToProps, {login}) (Login);
Upvotes: 1
Views: 1829
Reputation: 21
Make sure that in the login reducer of redux store , you have provided the "isAuthenticated" as initialState like the below..
const initialState = { isAuthenticated: false, };
function loginReducer(state = initialState, action){ .... }
Also make sure that you have included the loginReducer in the "combineReducers" function , if you are using multiple reducers for your redux store
Upvotes: 2
Reputation: 12787
Because you don't set the initial state of auth
in the redux store. So you need to add optional chaining like this:
isAuthenticated: state.auth?.isAuthenticated
Upvotes: 2