Reputation: 377
I want to invoke something like a function call inside of a response so that I can open up a modal. I'm using material ui for the modal.
The flow goes with something like
The modal exists as a separate component so i cannot do
.then( e => {
<Modal />
})
Tried including the modal hook in the same file but doesn't work like that.
axios
.post(`${url}`, {
email: email
})
.then(res => {
if (res.data.type === "account not found") {
<WarningModal />
} else if (res.data.type === "email sent") {
<SuccessModal />
}
});
Just want to invoke modal components on receiving response.
Upvotes: 3
Views: 12190
Reputation: 41634
Add 2 state variable for both modals and set them true in the axios call, also add the modal to the return.
const test = () => {
const [showSuccessModal, setShowSuccessModal] = useState(false)
const [showWarningModal, setShowWarningModal] = useState(false)
axios
.post(`${url}`, {
email: email
})
.then(res => {
if (res.data.type === "account not found") {
setShowWarningModal(true)
} else if (res.data.type === "email sent") {
setShowSuccessModal(true)
}
});
return (
<div>
<WarningModal open={showWarningModal}/>
<SuccessModal open={showSuccessModal} />
</div>
)
}
Upvotes: 2
Reputation: 608
What you want to do is this:
Modal
component to your component's render function. Like so:open
prop of the Modal
component to a state, call it openModal
. Now you have this.state.openModal.this.setState({openModal: true})
You should have something like this:
render() => {
return (
...
<Modal open={this.state.openModal}/>
)
}
Upvotes: 1
Reputation: 3551
As you may have noticed, the Modal
component from material-ui takes an open
prop indicating whether the modal is open or not.
So what you have to do is to put the modal somewhere in your JSX with the open
prop set to a boolean value coming from your component's state.
And when you receive the response from your HTTP call, you toggle this boolean to true, and the modal will appear.
Upvotes: 2