Reputation: 119
I am trying to call the function(update state) from modal hook in React js. But, it does not update the state. However, when I write alert inside the function it works but setState does not. What can be a problem????
Main Component
this.state = {
message: false
}
showMessage(){
alert(" hhh"); //works
// this.setState({message:true}) //does not work
}
<ExcludeHolidayModal confirmExHol={this.showMessage}/>
Modal
function ExcludeHolidayModal(props) {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => {setShow(true)};
const [date, setDate] = useState(new DateObject());
const excludeHolidays = (dates) => {
API.excludeHolidays(dates).then(() => {
handleClose();
setDate(new DateObject());
props.confirmExHol(); //Calling function here <------------
})
.catch((err) => {
if (err.status === 401) {
}
});
}
return (
<>
<Button onClick={handleShow} data-testid="help-button" variant="info">
</Button>
<Modal
show={show}
onHide={handleClose}
backdrop="static"
keyboard={false}
>
<Modal.Header closeButton>
<Modal.Title>Choose Holidays</Modal.Title>
</Modal.Header>
<Modal.Body>
<DatePicker
value={date}
onChange={setDate}
multiple={true}/>
</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={() => excludeHolidays(date)}>Send</Button>
</Modal.Footer>
</Modal>
</>
);
}
export default ExcludeHolidayModal;
Upvotes: 0
Views: 583
Reputation:
Please try this:
this.state = {
message: false
}
showMessage = () => {
// alert(" hhh"); //works
this.setState({message:true}) //does not work
}
<ExcludeHolidayModal confirmExHol={this.showMessage}/>
Upvotes: 2