Junior
Junior

Reputation: 13

"ReactJs" reset the State but not the unique id

I have a simple form and I need to reset the state after each submit but keep the old id and build on it (get the next id based on the previous one)

this.state = {
  id: this.nextUniqueId();
  name: "Jhon",
}   

hSubmit = () => {    
  this.setState({    
    id: ????
    name: "",    
  });
};    

render(){
  return(
    <div> 
      <form onSubmit={this.hSubmit}> 
        <input type= "submit" /> 
        <br/> 
      </form>
    </div>
  );   
}

Upvotes: 1

Views: 71

Answers (2)

Seth McClaine
Seth McClaine

Reputation: 10030

Just get the previous state id and add to it during your set state

hSubmit = () => {    
  this.setState({    
    id: this.state.id++,
    name: "",    
  }); 
} 

Upvotes: 1

Anas
Anas

Reputation: 5727

You can use functional setState https://reactjs.org/docs/react-component.html#setstate

this.setState((prevState) => ({
    id: prevState.id + 1, // or whatever
    name: "",
}));

Upvotes: 2

Related Questions