-
Notifications
You must be signed in to change notification settings - Fork 71
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Persist cart on refresh #58
base: main
Are you sure you want to change the base?
Conversation
// Trying to have one location to update the local storage when the cart state changes, but only when items are added or removed. | ||
// It doesn't make sense to overwrite the localstorage every time the page is loaded with the logic I have with state, above. | ||
// But this implementation isn't much better, since I'm reading from disk twice on first load, and then again every time the cart is updated. | ||
// The alternative that I'm aware of is to put it in the onClick actions for adding and removing from the cart, which probably makes more sense at this point in time. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're on the right track - linking the actions that update the cart to localStorage is what I would recommend, but with a slight twist.
instead of spreading the code to multiple components (as you stated), you can simply wrap the updateCart function in a new function. This new function can update the cart state, and also pass the new cart state straight into localStorage. Here is an example.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ohhh I think I see what you did there. That makes sense, I didn't think of handling state within another function. Thank you!
Hi @mattpauls 👋 I see you've completed 3/5ths of the issues. Let me know if you need any help! |
Addresses #2
I'd love some feedback on this one, if possible. I wasn't sure if I should put updating localStorage in an onClick() or whether to use a useEffect. Using the onClick method, at least the way I was implementing it, would mean I'd have to have the same code in two locations, but onEffect reads from disk more than I think is necessary. (I added some comments in the code)