Inside a Component, I have a Modal from which the user can do an update to some data through an API and then change the state of that main Component. Because there is a change in state, everything will re-render.
I would like to keep the modal open, so that I can show a success message.
The code would be something like this.
const Main = () => {
const [state, setState()] = useState();
return (
<Component state={state}>
<Modal onButtonClick={() => {
updateThroughApi().then(() => setState())} />
</Component>
)
}
When user clicks on modal's button, the state changes, and Component is re-rendered. Modal is rendered too, as it's inside.
I have thought of two possible solutions:
Move the modal outside of the component. This is a problem, as my actual code is not as simple as the example I posted. In my code, the modal opens on the click of a button
B, which is deep insideComponent. So, if I move the modal out fromComponent, I would have to pass the status and the action to change status (e.g. [open, setOpen]) through several components until button B (prop drilling).Another solution: On the action
onButtonClickI just do the API update, and use a new stateupdated = true; then,onModalClose, only if updated is true, I runsetStatesoComponentis rendered just after the modal is closed. But this solution seems a hack to me. There must be a better way.
Is there any better solution?