Local Storage Next JS Error but still works
Answered
SharpieMaster posted this in #help-forum
I am getting this error in my command line but everything is working on the webpage, how could I prevent the error from being listed as it is cluttering my command line
Answered by riský
it doesn't work because SSR is a thing that prerenders your page on the server before giving the page to client (to help SEO and users without JS), so you should use a
useEffect and useState ... or you can use next/dynamic13 Replies
"use client";
import { toast } from "sonner";
import { Button } from "./ui/button";
const ToastTest = () => {
return (
<div className="">
<Button
onClick={() => {
localStorage.setItem("test", "testt");
}}
>
ToastTest
</Button>
<div>{localStorage.getItem("test")}</div>
</div>
);
};
export default ToastTest;ok
it doesn't work because SSR is a thing that prerenders your page on the server before giving the page to client (to help SEO and users without JS), so you should use a
useEffect and useState ... or you can use next/dynamicAnswer
.. i was to slow in typing - i didn't see Phantom's message ;(
"use client";
import { toast } from "sonner";
import { Button } from "./ui/button";
import { useState } from "react";
const ToastTest = () => {
const [test, setTest] = useState(localStorage.getItem("test")); // This was the added code
return (
<div className="">
<Button
onClick={() => {
localStorage.setItem("test", "test");
}}
>
ToastTest
</Button>
<div>{test}</div>
</div>
);
};
export default ToastTest;make a useEffect that sets
setTestdon't look at the question (to know what to do) on the site, but rather the answer (more down)
try that now, i believe that it should work
it does
thank you
@SharpieMaster Click to see attachment
Solution: use useState and useEffect and set the state inside of the useEffect on page load to set the state to the wanted localstorage value