I think this is a better way to handle the situation. This is how I handle a situation like this.
In you component,
const [cart, setCart] = useState([]);
React.useEffect(() => {
async function init() {
const data = await localStorage.getItem('myCart');
setCart(JSON.parse(data));
}
init();
}, [])
the cart is updated when the page reloads but not when new item adds
or updates any existing items!
How can I achieve that, which is cart update instantly if any changes
into 'localStorage`?
When you add items, let's assume you have a method addItem()
async function addItem(item) {
// Do not update local-storage, instead update state
await setState(cart => cart.push(item));
}
Now add another useEffect()
;
useEffect(() => {
localstorage.setItem('myCart', cart);
}, [cart])
Now when cart state change it will save to the localstorage
addEventListener
on storage is not a good thing. Everytime storage change, in you code, you have to getItems and parsed it which takes some milliseconds to complete, which cause to slow down the UI update.
In react,
- first load data from
localstorage
/ database
and initialize the state.
- Then update the state in the code as you want.
- Then listen on state changes to do any task ( In this case save to localstorage )
If your addItem()
function is a child of the above component ( cart component ), then you can pass the setItem
funtion as a prop / or you can use contex API or else use Redux
UPDATE
If addCart
is another component
- if the component that has
addCart
function is a child component of cart
component, use props
- https://reactjs.org/docs/components-and-props.html
- if the component that has
addCart
function is NOT a child component of cart
component, use context api to communicate between components - https://reactjs.org/docs/context.html
- if you want to manage your data in clean & better way, use https://redux.js.org/
According to the use case, I assume your addItem
function declared in a Product
component..
I recommend you to use Redux to handle the situation.
UPDATE
As @Matt Morgan said in comment section, using context API is better for the situation.
But if your application is a big one ( I assumed that you are building an e-commerce system ) it may be better to use a state management system like Redux. Just for this case, context API will be enough