Reputation: 133
I'm trying to implement an eventlistener that triggers an useEffect-function to render a shopping bag. At the moment the shopping bag only appears after reloading the page. This should happen instantly instead. I've build a sandbox for my problem: https://codesandbox.io/s/vigilant-oskar-drsvy?file=/src/App.js. When clicking the "Click it" button nothing appears but when reloading the page.
Here is also the code:
export default function App() {
const [storageData, setStorageData] = useState(localStorage.getItem("alert"));
useEffect(() => {
setStorageData(localStorage.getItem("alert"));
}, []);
//insert eventlistener to dependency array of useEffect
return (
<div className="App">
<button
onClick={() => {
localStorage.setItem("alert", "ShoppingBag");
}}
>
click it
</button>
<div>{storageData}</div>
</div>
);
}
Upvotes: 0
Views: 335
Reputation: 64657
You need to kind of inverse how you are doing it - when you storageData
changes, you should do localStorage.setItem
, and then you do setStorageData
and your useEffect
will pick up the change and save it.
https://codesandbox.io/s/naughty-herschel-469i1
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const [storageData, setStorageData] = useState(localStorage.getItem("alert"));
useEffect(() => {
localStorage.setItem("alert", storageData);
}, [storageData]);
//insert eventlistener to dependency array of useEffect
return (
<div className="App">
<button
onClick={() => {
setStorageData("ShoppingBag");
}}
>
click it
</button>
<div>{storageData}</div>
</div>
);
}
Upvotes: 2