How to do atomWithReducer + localStorage correctly with Next.Js
See original GitHub issueI’ve been trying to achieve the way of doing that, the logic is the general logic that if its SSR, send true, otherwise send the localStorage value.
This is my code -
import { atomWithReducer } from "jotai/utils";
const isSSR = typeof window === "undefined";
export const gtAtom = atomWithReducer(
isSSR ? true : localStorage.getItem("gt"),
(_prev, newGt: string) => {
localStorage.setItem("gt", newGt);
return newGt;
}
);
Then using it like this -
const [gt, setGt] = useAtom(gtAtom);
But when its always showing value as null whenever i try to load the page. is there something wrong the way I’m doing it?
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (3 by maintainers)
Top Results From Across the Web
How To Use LocalStorage in Next.js
In Next.js, you can use LocalStorage through the window interface, and wrap this around a custom hook to use throughout your code.
Read more >Next.JS - Access `localStorage` before rendering page
You can do something like this: Use a variable in the state to prevent the page from being rendered; Use componentDidMount to load...
Read more >Accessing LocalStorage in NextJS
I recently migrated a Content Management System from Create React App to NextJS in order to score some SEO points.
Read more >Jotai vs. Recoil: What are the differences?
Jotai and Recoil both have their benefits. This article compares the state management libraries to help you decide what's best for you.
Read more >Having trouble with state and using localStorage with a ...
getSettings() { // get from local storage if (process.browser) { const ... next is a great framework to handle rendering the correct ......
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@dlindenkreuz hey sorry about it, i just did a useEffect that will check if the value is undefined, if it’s check again or try to set state again. Sorry I tried finding the exact code where i did it, but it was missing/not able to find it.
I added a recheck with the help of useEffect and my problem got solved. And thanks for creating such a good library.