Snackbar shows empty message before clearing

Viewed 105

I'm showing a Material-UI snackbar, using a message from Redux:

const MySnackBar = () => {
  const message = useSelector(({ data }: RootState) => data.message)
  
  return (
    <Snackbar open={ !!message }>
      <Alert variant={ 'filled' }>{ message }</Alert>
    </Snackbar>
  )
}

I have redux actions that write the message to the store, and then clear the message (message = '') after a timeout.

export const showMessage = (dispatch: any, message: string) => {
  dispatch(setMessage(message))
  setTimeout(() => dispatch(clearMessage()), 3000)
}

This works, except that before the snackbar actually disappears, it shows with the blank message.

I guess this is because of how transition animations work, where it the snackbar starts to animate out once open is set to false.

What's the best way to implement the snackbar so that it hides "correctly"?

I imagine one solution would be having a boolean showSnackbar entry in my store, and not clearing the message. This seems slightly clunky, requiring two pieces of information rather than one, and I don't like the smell of leaving the message in the store when it's not being shown.

But I imagine that maybe that's still the best way despite those "shortcomings."

What do people like to do for this?

0 Answers
Related