Support
Quality
Security
License
Reuse
Coming Soon for all Libraries!
Currently covering the most popular Java, JavaScript and Python libraries. See a SAMPLE HERE.
kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Static E-commerce site built using GatsbyJs
To use
SANITY_TOKEN=YOUR_KEY_HERE
QUESTION
React state object turning into "[object Object]" on refresh using sessionStorage
Asked 2022-Mar-23 at 14:53I'm working on a dummy fullstack ecommerce app using Postgres, Express and React whilst going through a fullstack course. This question is pretty specific to React.
On login to the app I can successfully create or retrieve a cart from the db and save it to state. It's being saved as a normal object:
Cart: {id: 2, user_id: 159, product_count: 0, price: '£0.00'}
-From Chrome Dev Tools: Extensions React Developer Tools.
I'm then using React useEffect hooks to persist this state in sessionStorage:
App.js
useEffect(() => {
if (sessionStorage["cart"]) {
setCart(window.sessionStorage.getItem("cart"));
}
}, []);
useEffect(() => {
window.sessionStorage.setItem("cart", cart);
}, [cart]);
Whenever I refresh the page or go to another route the normal object seems to be turning into the string: "[object Object]".
I know it has something to do with the way I'm saving the cart state variable into the localStorage but I'm not familiar with it enough to know exactly where this is happening or how to fix it so any help would be appreciated.
I've tried changing the assignment variables within the useEffect calls to include trying to save the item as an object, but I'm not familiar enough with sessionStorage to know what's happening behind the scenes.
ANSWER
Answered 2022-Mar-23 at 14:53When you store the object to storage, call JSON.stringify(cart) to convert from an object to a string.
When you read the object from storage, it's const cart = JSON.parse(cartString)
to convert from the string back into an object.
Like so:
useEffect(() => {
if (sessionStorage["cart"]) {
setCart(JSON.parse(window.sessionStorage.getItem("cart")));
}
}, []);
useEffect(() => {
window.sessionStorage.setItem("cart", JSON.stringify(cart));
}, [cart]);
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported