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

206
Visualizações
I want to loop in an array in the state and check if the input is exist in it

I tried to build this method addgamer() to check if the username exists in the gamers array onClick add button and if he is , i want it don't add his info as an object in the array, i want to know why it didn't work ? ....i created this enterdata() method to get the values of these three gamer info onChange the values of their inputs

class App extends Component {
  state= {
    gamer:{
          FirstName:"",
          LastName: "",
          UserName: "",
    },
    gamers:[],
  }

  enterdata = (event)=> {
    const {name, value} = event.target;
    this.setState((prevstate)=>({
        gamer: {...prevstate.gamer,[name] : value},  
    }))
  }
  
  addgamer = (event) =>{
  event.preventDefault();
  for(let i = 0;i<this.state.gamers.length; i++){
    if(this.state.gamer.UserName === this.state.gamers[i].UserName){
        return false; 
    }else{
        this.setState(prevstate =>({
        gamers: [...prevstate.gamers, this.state.gamer],
        gamer: {FirstName:"", LastName: "", UserName: ""},
  }))
    }
  }  
  
  }
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

The issue here is that you are adding the gamer every time the username is not found. What you should do is set a flag to see whether the username was found in the gamers list or not, and then do the setState to add the new gamer if the username was not found, like so:

let found = false;
for(let i = 0;i<this.state.gamers.length; i++){
    if(this.state.gamer.UserName === this.state.gamers[i].UserName){
        found = true;
        break;
    }   
}
// alternatively: let found = this.state.gamers.find(gamer => this.state.gamer.UserName === gamer.UserName)
if (!found) {
    this.setState(prevstate =>({
        gamers: [...prevstate.gamers, this.state.gamer],
        gamer: {FirstName:"", LastName: "", UserName: ""},
    }))
}
about 4 years ago · Santiago Gelvez 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