I am relatively new to react and am trying to find out the proper way to handle changing the state of an input checkbox.
I have a checkbox that is either true or false depending on a boolean from a database. I currently am using defaultChecked to either have the checkbox already set to true or false when the user loads the state. I tried using checked and the checkbox would fire off my onClick function and update the database but the checkbox would stay in the initial boolean state.
So when you click on the checkbox, the onClick event calls a function that should update the Database boolean to either true or false. My issue is, I don't want the checkbox to go to true or false if the database doesn't actually update. If there is a communication error on update and response.sucess is false the checkbox should stay on the value it originally loaded the state with. The checkbox should only switch when response.success is true. Any suggestions on the proper way to do this? I believe I just have to update the state but a little confused on how to go about that with a checkbox and a database. Thanks.
<input
id="database-boolean"type="
checkbox"defaultChecked={this.props.dataBaseBoolean}
handleUpdate={this.handleUpdateDataBaseBoolean}
onClick={(e) => this.handleUpdateDataBaseBoolean(e)}
/>
handleUpdateDataBaseBoolean = (e) => {
const {key} =this.props;
this.props.updateDataBaseBoolean(key, e).then((response) => {
if(response.success) {
toastr.success(response.message, { timeOut: 2000, position: 'top-center'});
}else{
toastr.error("Failed to update boolean", { timeOut: 2000, position: 'top-center'});
}
}
)};
Aucun commentaire:
Enregistrer un commentaire