Can anyone explain to me please why using this.initialState knowing that I am using class component here in React JS ?
class Inscription extends Component {
constructor(props) {
super(props);
this.state = {
pseudo: '',
email: '',
password: '',
formErrors: {}
};
this.initialState = this.state;
}
Imagine having a form with multiple inputs and eventually user submits all the data. After succesfull submit, you want to reset everything in the form. The easiest way is to do this.state = this.initialState so you don't need to define initialState two times.
Instead of adding the initialState to Class itself I would define it outside of the class.
const initialState = {
pseudo: '',
email: '',
password: '',
formErrors: {}
};
class Inscription extends Component {
constructor(props) {
super(props);
this.state = initialState;
}
onSubmit(){
// do backend call
// some others events
// eventually reset the state
this.state = initialState;
}
}