Last active
October 9, 2021 18:07
-
-
Save tomfa/1881e789120830ee8a805f3dd2959a25 to your computer and use it in GitHub Desktop.
NextJS storing state in URL
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 { useQueryState } from 'next-usequerystate'; | |
import { useEffect } from 'react'; | |
const defaultData = { | |
name: 'Robert Paulsen', | |
age: 37, | |
} | |
const parse = (query) => { | |
try { | |
const json = JSON.parse(String(query)); | |
return { | |
name: json.name || defaultData.name, | |
age: json.age || defaultData.age, | |
}; | |
} catch { | |
return defaultData; | |
} | |
}; | |
const serialize = (catInfo) => JSON.stringify(catInfo); | |
const queryStateOptions = { parse, serialize } | |
export default () => { | |
const [data, setData] = useQueryState('data', queryStateOptions); | |
useEffect(() => { | |
if (!data) { | |
setData(defaultData); | |
} | |
}, []); | |
if (!data) { | |
return null; | |
} | |
return ( | |
<> | |
<h1> | |
Hello, {data.name || 'anonymous visitor'}, aged {data.age}! | |
</h1> | |
<input | |
value={data.name || ''} | |
onChange={(e) => setData(existing => ({ | |
...existing, | |
name: e.target.value | |
}))} | |
/> | |
<button onClick={() => setData(defaultData)}>Clear</button> | |
</> | |
); | |
}; |
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 { useQueryState } from 'next-usequerystate' | |
export default () => { | |
const [name, setName] = useQueryState('name') | |
return ( | |
<> | |
<h1>Hello, {name || 'anonymous visitor'}!</h1> | |
<input value={name || ''} onChange={e => { | |
// Note: do not try to call two different useQueryState | |
// functions in one render. Only the last will apply. | |
setName(e.target.value) | |
}} /> | |
<button onClick={() => setName(null)}>Clear</button> | |
</> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment