Helcio Oliveira
Helcio Oliveira

Reputation: 34

e.target is null, when i'm using setState

I want to change my state, the user properties, when the you change the field on the form I want it to change the proper value on user.

My element that I'm passing the function to, is to handle the value and fill the state in the parent component.

Ex: user type password. I want the user object to keep the same, but the user has to change.

state = {
      signUp: true,
      user:{
        name: '',
        password: '',
        email: '',
        userName: ''
      }
    }

handleChange = e =>{        
    this.setState(prevState => ({
      user: {
        ...prevState.user,
       [e.target.name] : e.target.value
      }
    } 

    ));
  }



 export default function SignupForm({handleSignup, handleChange}) {
    return (
        <div>
            <div className='login-page__main__cadastro'>


            <h4>
                 Cadastre-se para ver<span className='br'><br></br></span> fotos e vídeos dos seus <span className='br'><br></br></span> amigos.
                 </h4> 

                 <form className='login-page__main__cadastro__form'>
                  <input className='form-cadastro-item' onChange={handleChange} name='email' type='email' placeholder='email'></input>
                  <input className='form-cadastro-item' onChange={handleChange} name='name' type='text' placeholder='Nome completo'></input>
                  <input className='form-cadastro-item' onChange={handleChange} name='userName' type='text' placeholder='Nome de usuário'></input>
                  <input className='form-cadastro-item' onChange={handleChange} name='password' type='password' placeholder='Senha'></input>

                 <button onClick={handleSignup} className='btn-primary'>
                 Cadastrar-se

                 </button>

                 </form>
            </div>
        </div>
    )
}

I'm getting an error: e.target is null.

Upvotes: 0

Views: 1490

Answers (1)

Ismael Padilla
Ismael Padilla

Reputation: 5576

You should either save the value to another variable, or use e.persist():

handleChange = e =>{    
    let myName = e.target.name;
    let myValue = e.target.value;    
    this.setState(prevState => ({
        user: {
            ...prevState.user,
            [myName] : myValue
        }
    })); 
}

This is because in React uses synthetic events for performance reasons. From the event pooling section of the docs:

The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

Upvotes: 2

Related Questions