Reset autohide timer in Snackbar when Re-Rendering

Viewed 320

This is my snackbar component:

<Snackbar open={open}
  autoHideDuration={2000}
  onClose={handleClose}
  anchorOrigin={{ vertical: 'top', horizontal: 'center' }}>
    <SnackbarContent aria-describedby="message-id2"
      className={classes.snackbarStyleViaNestedContent}
      message={props.single_message[0]}
      action={action} />
</Snackbar>

I am calling it from another component which sends down data every 1-3 seconds randomly. I want to display a snackbar for 2 seconds everytime but am not able to do so since the autoHideDuration doesn't reset on every re-render. Is there a way I can reset the autoHideDuration timer on every re-render. Any help is appreciated.

1 Answers

You could probably use a state and a javascript timeout, as I described in your other question here.

var timeout;
const [open, setOpen] = useState(false);

<Button
  onClick={() => {
    setOpen(true);
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      setOpen(false);
    }, 2000);
  }}
/>
<Snackbar
  open={open}
  onClose={() => setOpen(false)}
  message="Test snackbar"
/>

Just replace the button with the function you use to get the data

Related