Home > Net >  I want to loop in an array in the state and check if the input is exist in it
I want to loop in an array in the state and check if the input is exist in it

Time:06-14

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: ""},
  }))
    }
  }  
  
  }

CodePudding user response:

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: ""},
    }))
}

CodePudding user response:

You may use

this.state.gamers.find(x => x.UserName === this.state.gamer.UserName); 

to check if user exists. This would look a bit cleaner

  • Related