I want the snackbar to timeout in 2 seconds only if the component doesn't update. If it updates I want the timer to reset if it hasn't reached 2 seconds yet.
useEffect(() => {
setOpen(true)
},[props.single_message])
return(
<div>
{props.single_message.length !== 0
?
<Snackbar open={open} autoHideDuration={2000}
onClose={() => setOpen(false)}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }} >
<SnackbarContent aria-describedby="message-id2"
className={classes.snackbarStyleViaNestedContent}
message={props.single_message[0]}
action={action}
/>
</Snackbar>
:
null
}
</div>
)
How can I reset the autoHideDuration on a component update if the autoHideDuration hasn't completed yet. If not possible with autoHideDuration, is there another way?
I think the best way would be something like this:
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"
/>
However maybe something like this (using the current time) could work:
const [closeTime, setCloseTime] = useState(0);
<Button onClick={() => setCloseTime(Date.now() + 2000)} />
<Snackbar
open={closeTime > Date.now()}
onClose={() => setCloseTime(0)}
message="Test snackbar"
/>