From 1b9e624004cfb64135b744f877e5fa87e5810abd Mon Sep 17 00:00:00 2001 From: Sebastien Castiel Date: Tue, 9 Jan 2024 08:53:51 -0500 Subject: Ask the user who they are when opening a group for the first time (#7) --- src/lib/hooks.ts | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/lib/hooks.ts (limited to 'src/lib/hooks.ts') diff --git a/src/lib/hooks.ts b/src/lib/hooks.ts new file mode 100644 index 0000000..02e2543 --- /dev/null +++ b/src/lib/hooks.ts @@ -0,0 +1,42 @@ +import { useEffect, useState } from 'react' + +export function useMediaQuery(query: string): boolean { + const getMatches = (query: string): boolean => { + // Prevents SSR issues + if (typeof window !== 'undefined') { + return window.matchMedia(query).matches + } + return false + } + + const [matches, setMatches] = useState(getMatches(query)) + + function handleChange() { + setMatches(getMatches(query)) + } + + useEffect(() => { + const matchMedia = window.matchMedia(query) + + // Triggered at the first client-side load and if query changes + handleChange() + + // Listen matchMedia + if (matchMedia.addListener) { + matchMedia.addListener(handleChange) + } else { + matchMedia.addEventListener('change', handleChange) + } + + return () => { + if (matchMedia.removeListener) { + matchMedia.removeListener(handleChange) + } else { + matchMedia.removeEventListener('change', handleChange) + } + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [query]) + + return matches +} -- cgit v1.3