Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
setState not working properly when using value={} in input field

I am using React JS. I am setting the state, however, there is a problem, in the value={} part of the input field.

Here is my code:

import React from 'react';



class SomeClass extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            passCode: {
                email: "Email",
                password: "Password"
            },
            errorMessage: ''
        };
    }



    handleChange = (event) =>{
        console.log(`input detected`);
        let request = Object.assign({},this.state.passCode);
        request.email = event.target.value;
        request.password = event.target.value;
        this.setState({passCode: request});
     }


    
    
    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                
                    <label>Email Address</label>
                    <input type="text" value={this.state.passCode.email} onChange={this.handleChange} placeholder="Enter Email Address" />
  
                    <label>Password</label>   
                    <input type="password" value={this.state.passCode.password} onChange={this.handleChange} placeholder="Enter One Time Password" />

                <Button type="submit">
                    Sign In</Button>
            </form>
        );
    }
    
}


export default SomeClass;

My Question:

I have is for the value attribute of the input fields, I think setState is not working properly:

In the passCode object of the state. When I type the email, both fields get set to what I typed in the email field. When I type the password, both fields get set to what I typed in the password field.

What's the reason for such problem?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

setState is working properly; your handleChange isn't. You're setting both email and password to the value of the input regardless of which input the change occurred on. Instead, you want to update just the relevant property. To do that, I'd add name attributes to the input elements (name="email" and name="password"), then:

handleChange = ({currentTarget: {name, value}}) =>{
    console.log(`input detected`);
    this.setState(({passCode}) => {
        return {passCode: {...passCode, [name]: value}};
    });
};

Key bits there are:

  • It only updates the property the change related to, keeping the other one unchanged, by using the name of the input.
  • It uses the callback version of setState (best practice since we're setting state based on existing state).
about 4 years ago · Juan Pablo Isaza Relatório

0

Your funtion handleChange is wrong. You should update like this with using name:

handleChange = (event) => {
  console.log(`input detected`);
  const { name, value } = event.target;
  this.setState({ passCode: { ...this.state.passCode, [name]: value } });
};

And set name to input:

<input type="text" value={this.state.passCode.email} onChange={this.handleChange} placeholder="Enter Email Address" name="email" />
<input type="password" value={this.state.passCode.password} onChange={this.handleChange} placeholder="Enter One Time Password" name="password" />
about 4 years ago · Juan Pablo Isaza Relatório

0

The methods they gaved are good, but I still suggest that you separate the methods of changing the two, maybe it will be much better.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda