Skip to content

Instantly share code, notes, and snippets.

@all12jus
Created September 5, 2021 12:21
Show Gist options
  • Save all12jus/1cad7c0828f5185afca546ad76a67985 to your computer and use it in GitHub Desktop.
Save all12jus/1cad7c0828f5185afca546ad76a67985 to your computer and use it in GitHub Desktop.
getCartFromLocalStorage -- React
const LocalStorageCartKey = "CartList";
const getCartFromLocalStorage = () => {
try {
let items = JSON.parse(localStorage.getItem(LocalStorageCartKey));
if (items === null || items === undefined)
{
return [];
}
return items;
} catch (e) {
console.warn("Parse Error, in getCartFromLocalStorage, ", e);
return [];
}
};
const [ cartItems, setCartItems ] = useState(getCartFromLocalStorage());
const cartSubject = new Subject([]);
cartSubject.subscribe(newCart => {
setCartItems(newCart);
localStorage.setItem(LocalStorageCartKey, JSON.stringify(newCart));
console.log(newCart);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment