Created
September 5, 2021 12:21
-
-
Save all12jus/1cad7c0828f5185afca546ad76a67985 to your computer and use it in GitHub Desktop.
getCartFromLocalStorage -- React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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