I want to show a div which has an error message from backend. But on changing state variable component does not re render.
const [hasValidationError, setHasValidationError] = useState<boolean>(false);
const [hasSubmissionError, setHasSubmissionError] = useState<boolean>(false);
const handleButtonClick = () => {
if (state.name) {
setHasSubmissionError(false);
setHasSubmissionValidationError(false);
callBackend(id)
.then((newFoo: Foo[]) => {
//do something
})
.catch((err) => {
setHasSubmissionError(true); //This is not working
console.log("In catch"); // this is logging
console.log(hasSubmissionError); //this is logging false not sure why
});
} else {
setHasValidationError(true); //This is working
// if I do setHasSubmissionError(true); here div starts showing up but if I do this from above catch clause
}
};
return (
<div>
{hasValidationError && (
<div className={styles.errorDiv}>
There is a validation error this is showing correctly
</div>
)}
{hasSubmissionError && (
<div className={styles.errorDiv}>
There is a submission error this div never shows
</div>
)}
<Input value={state.name}/>
<Button onClick={setHasValidationError} className={styles.button}>
</Button>
</div>
);
I created this react playground https://playcode.io/1539343