Home > other >  React - Error : TypeError: Cannot read properties of undefined (reading 'then')
React - Error : TypeError: Cannot read properties of undefined (reading 'then')

Time:09-28

Hi i am new to react js and i have this problem on my login page, TypeError: Cannot read properties of undefined (reading 'then') the problem comes from the function handleSubmit() specialy from .then(user => {)} can you help me please

PS : im using firebase

   import React, {useState, useEffect, useContext} from 'react'
   import { Link } from 'react-router-dom'
   import {FirebaseContext} from '../Firebase'
   const Login = (props) => {

   const firebase = useContext(FirebaseContext);

   const [email, setEmail] = useState('');

   const [password, setPassword] = useState('');

   const [btn, setBtn] = useState(false);

   const [error, setError] = useState('');

useEffect(() => {
    if(password.length > 5 && email !==""){
        setBtn(true)
    }else if(btn){
        setBtn(false)
    }
}, [password, email, btn])

const handleSubmit = e => {
    e.preventDefault();
    
    firebase.loginUser(email, password)
    .then((user) => {
        setEmail('');
        setPassword('');
        props.history.push('/welcome');
    })
    .catch(error => {
        setError(error);
        setEmail('');
        setPassword('');
    })
}

return(myhtml)
export default Login;

CodePudding user response:

the server must have responded with null.

try

firebase.loginUser(email, password)
.then((user) => {
    if(!user) return;
    setEmail('');
    setPassword('');
    props.history.push('/welcome');
})
.catch(error => {
    setError(error);
    setEmail('');
    setPassword('');
})

if you are rendering a state on the screen you should check that the value is not null

example

{email ? email : 'does not exist'}

CodePudding user response:

firebase.loginUser(email, password) returns undefined. You try to access the then property of an undefined object.

CodePudding user response:

1.Do you call anywhere you method const handleSubmit ? 2.Second you `const handleSubmit = e => { e.preventDefault();

firebase.loginUser(email, password)
.then((user) => {
    setEmail('');
    setPassword('');
    props.history.push('/welcome');
})
.catch(error => {
    setError(error);
    setEmail('');
    setPassword('');
})

}` in your then((user)) where is coming from user ? you don't have user in posted , or is a param in then ? if is param then is should be in this way.

user.setPassword('')
  • Related