Created
September 3, 2024 23:11
-
-
Save WomB0ComB0/75290c03bc43642f3b2ac238d1a18dba to your computer and use it in GitHub Desktop.
Query param state management
This file contains hidden or 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
import { useQueryState } from 'nuqs'; | |
import { useCallback } from 'react'; | |
import { useIsomorphicLayoutEffect } from 'usehooks-ts'; | |
import { v4 as uuidv4 } from 'uuid'; | |
export const usePersistedId = ( | |
key: string, | |
): { | |
id: string | null; | |
clearId: () => void; | |
setPersistedId: (newId: string) => void; | |
generateNewId: () => string; | |
} => { | |
const [id, setId] = useQueryState(key); | |
const clearId = useCallback(() => { | |
if (typeof window !== 'undefined') { | |
sessionStorage.removeItem(key); | |
} | |
setId(null); | |
}, [key, setId]); | |
const setPersistedId = useCallback( | |
(newId: string) => { | |
if (typeof window !== 'undefined') { | |
sessionStorage.setItem(key, newId); | |
} | |
setId(newId); | |
}, | |
[key, setId], | |
); | |
const generateNewId = useCallback(() => { | |
const newId = uuidv4(); | |
setPersistedId(newId); | |
return newId; | |
}, [setPersistedId]); | |
useIsomorphicLayoutEffect(() => { | |
if (typeof window !== 'undefined') { | |
const existingId = sessionStorage.getItem(key); | |
if (existingId && !id) { | |
setId(existingId); | |
} | |
} | |
}, [key, id, setId]); | |
return { id: id ?? null, clearId, setPersistedId, generateNewId }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment