Using Local Storage for handling in React

Wanting to store data, but not necessarily wanting to POST/GET?

Awesome. This can be done by using local storage.

I ran into this issue when I was trying to make transactions in my ski resort app. I wanted to use variables that I was already using in my “Sale POST”.

  • **Something to note*** If you are looking to make a transaction model in Rails, it will not work. Rails already has methods associated with “Transaction”. So you will need to name it something else. In my case, I used Sale.rb for my model.

In my “Sale POST”, I used set items like this.

I set my state to :

const [sale, setSale] = useState({

customer_id: JSON.parse(localStorage.getItem(‘customer_id’)),

user_id: currentUser.id,

product_ids: []

})

On the customer I was using, I was able to pull the set customer from local storage. I stored this on a click in my code.

const handleAddCustomerToCart = (customerToAdd) => {

const customerInCart = customers.find((customer) => customer.id === customerToAdd.id)

setCartCustomer(customerInCart)

localStorage.setItem(‘customer_id’, customerToAdd.id);

}

Storing an item to localStorage is easy. You need to use the code localStorage.setItem()

Inside of the setItem function, you need to name what you are saving to local storage. In the case above, I used ‘customer_id’. You also need to save a value to this key. For me, it was a value passed into my click function with an id.

Some other important localStorage functions include: removeItem and getItem.

I used getItem in my sale state to pull the id from local storage.

I also used removeItem in my sale post. After posting a transaction, I cleared the cart and removed the customer associated.

These are some beneficial ways to store data when you don’t necessarily need to post to a server.

The New Guy!