How to use add and access data in LocalStorage in Gatsby

Viewed 2094

I have a Gatsby app where I am creating a little shopping cart. In order to make the data persist whenever a user clicks on add to cart, I want to use local storage. I use the below code for this

import React from 'react';

export default function OrderItem() {
    const addToCart = (selectedItem) => {
        localStorage.setItem('cartItems', selectedItem);
    };

    return (
        <div>
            <button onClick={addToCart}>Add </button>
        </div>
    );
}

But this gives me a localStorage.setItem is not a function error.

Anyone have any idea on why this might be happening?

1 Answers

localStorage.setItem is not a function means that you do have a localStorage object, but that object in turn doesn't have a setItem. That should never be able to happen in a browser.

Gatsby will not modify localStorage either. So the most likely problem is that you've declared another variable called localStorage that is overriding the one by the browser.

Try doing a console.log(localStorage) in your code. You should see something like this in Chrome. If you don't, you likely have another variable in scope with that name.

enter image description here

Related