Home > Software design >  Prevent text from updating until component (Dialog, Snackbar, etc.) has closed
Prevent text from updating until component (Dialog, Snackbar, etc.) has closed

Time:02-25

I've implemented a Dialog component which displays the values of some state variables.

When the Dialog closes, the state variables are reset to default. The problem is that although the Dialog closes in less than a second, it's still enough time to see that the text has changed.

Is there a way to stop the text from changing until the Dialog has actually closed? I tried setting the dialogOpen state variable to false first, before resetting the other state variables to default, but it didn't help since it happens too fast and React asynchronously batches the state changes anyway.

<Dialog
    open = {dialogOpen}
    onClose = {() => handleDialogClose()}
    ... />

handleDialogClose():

const handleDialogClose = () =>
{
    setDialogOpen(false)
    setStateVariables(DEFAULT_VALUES)
}

I think this issue is general to more components than just the Dialog, since it also happens with text that appears on Snackbar components. A general solution to all of it would be best, but anything will help.

Edit: The Dialog uses a Fade transition, where the timeout.exit delay is about 200ms. Using setTimeout() to delay updating the state variables works, per @technophyle's answer below. The delay passed to setTimeout() can be 0 and the extra time is still enough to prevent the change being seen.

CodePudding user response:

This is a tricky issue to resolve gracefully if your Dialog component has a CSS transition animation.

One solution (though not pretty) if you know the transition duration:

const handleDialogClose = () =>
{
    setDialogOpen(false)
    setTimeout(() => {
        setStateVariables(DEFAULT_VALUES)
    }, TRANSITION_DURATION_MS)
}

CodePudding user response:

You can deal with changing the state variable as a side effect

useEffect(() => {
    if(!dialogOpen){
        setStateVariables(DEFAULT_VALUES);
    }
}, [dialogOpen]);
  • Related