Created
July 8, 2021 08:15
-
-
Save tjinlag/6249d2e1f58b981db0dc2571eae10dca to your computer and use it in GitHub Desktop.
custom hook: useToastContent - using for toast a message, and then automatically hide it (after a timeout, eg: 2s)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const useToastContent = (timeout = 2e3) => { | |
const [content, setContent] = useState(''); | |
const timer = useRef(); | |
useEffect(() => { | |
return () => { | |
if (timer && timer.current) { | |
clearTimeout(timer.current); | |
} | |
} | |
}, []); | |
const toast = (value) => { | |
setContent(value); | |
timer.current = setTimeout(() => { | |
setContent(''); | |
}, timeout); | |
} | |
const close = () => { | |
setContent(''); | |
if (timer && timer.current) { | |
clearTimeout(timeout.current); | |
} | |
} | |
return [content, toast, close]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment