Store and Load Cart State from Local Storage to Persist Cart Data When Reloading the Page

InstructorColby Fayock

Share this video with your friends

Send Tweet

Our cart application is working well. One thing you might have noticed is that if you reload a page, the current state of the application gets wiped out.

This is where Browser Local Storage comes in handy to persist data through refreshes of the application.

This is a side effect that we want to happen any time state changes in our app. React handles this with the useEffect hook. In this hook, we will use the window.localStorage API to set and get cart data in our application.

fauno F
~ 3 years ago

thanks master, I'm following this lovely course. then I got a code structure question

  • why do you choose not to use the same '&&' structure like in the code below?
const data = state_from_storage && JSON.parse(state_from_storage)
data && update_cart(data)
Colby Fayockinstructor
~ 3 years ago

why do you choose not to use the same '&&' structure like in the code below?

hey @fauno - just personal preference! I like having an explicit if statement wrapped around function invocations

~ 3 years ago

How are you able to implement the function:

         <button onClick={checkout}>
                <a> (subtotal).toFixed(2)} </a>
            </button>

without returning an error like:

Unhandled Runtime Error

IntegrationError: Client-only Checkout does not support prices with usage_type=metered in items[0].