Last active
August 15, 2023 21:03
-
-
Save tomsoderlund/c352b561df7de0330ec3b36dcc26fe5b to your computer and use it in GitHub Desktop.
Like useState hook, but saves current state in browser search bar (Next.js router query)
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
// import useRouterQueryState from '../hooks/useRouterQueryState' | |
// const [myState, setMyState] = useRouterQueryState(propertyName, defaultValue) | |
import { useState, useEffect } from 'react' | |
import { useRouter } from 'next/router' | |
function useRouterQueryState (key, defaultValue) { | |
const router = useRouter() | |
// Get initial state from router query or default value | |
const [state, setState] = useState(router.query[key] ?? defaultValue) | |
useEffect(() => { | |
// Update state when router query changes | |
setState(router.query[key] || '') | |
// Also, set up an event listener for route changes | |
const handleRouteChange = (url) => { | |
setState(router.query[key] || '') | |
} | |
router.events.on('routeChangeComplete', handleRouteChange) | |
return () => { | |
router.events.off('routeChangeComplete', handleRouteChange) | |
} | |
}, [router.query]) | |
const setQueryState = (value) => { | |
setState(value) | |
// Update the URL without navigating | |
const queryWithoutKey = { ...router.query } | |
delete queryWithoutKey[key] | |
router.push({ | |
pathname: router.pathname, | |
query: { | |
...queryWithoutKey, | |
...(value && { [key]: value }) | |
} | |
}, undefined, { shallow: true }) | |
} | |
return [state, setQueryState] | |
} | |
export default useRouterQueryState |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment