LocalStorage

Gabriel Castro
3 min readApr 3, 2021

You ever just want to build a project without having to go thru the hassle of setting up a backend to store all your inputs? Enter localStorage. LocalStorage allows developers to access read-only objects saved across the browser session. The great part of localStorage is that unlike sessionStorage which gets cleared every time the page reloads, localStorage will not clear unless you clear it yourself or have a function that does so. This is obviously not ideal for big projects for scalability, but if you’re just looking to see what data may look like saved against your current application, localStorage provides a great solution.

How to use it?

OK, so we understand the benefits of localStorage, lets look at some examples on how to go about using it.

In order to set your localStorage you would use the SetItem() which allows you to pass a key name and value that will storage this as an object or update the keys value.

localStorage.setItem('user', 'Jason')

In order to read localStorage you would use getItem(), this allow you to set a variable to a key that will return the keys value, or null.

var aUser = storage.getItem(user)

to remove an item for localStorage you would use removeItem(), when passed a key name, will remove the object in question.

storage.removeItem(user)

Finally you can clear LocalStorage with

localStorage.clear()

Real Use Application

Lets build a quick app that allows us to track income/expenses for transaction that are inputted.

Setting localStorage …

import { useState, useEffect } from "react";function App() {const [transaction, setTransaction] = useState({
description: '',
amount: ''
})
const [transactionList, setTransactionList] = useState(
JSON.parse(localStorage.getItem('transactionList')) || []
)
const [balance, setBalance] = useState('')
const [income, setIncome] = useState(JSON.parse(localStorage.getItem('income'))
)
const [expense, setExpense] = useState(JSON.parse(localStorage.getItem('expense')))

Here we are setting up all are useState hooks with localStorage, this will allow us to to have these variables saved in localStorage to prevent them from being cleared unless requested.

Next we will go ahead and set up our additional functoins to update our form, retrieve our balance given income/expense and setting up the useEffect to render all the localStorage and lastly clear our budget.…

.....
const updateForm = e => {
setTransaction({
...transaction,
[e.target.name]:
e.target.type === 'number' ? parseInt(e.target.value) : e.target.value
})
}
const getBalance = () => {
const amounts = transactionList.map(i => i.amount)
const money = amounts.reduce((acc, item) => (acc += item), 0).toFixed(2)
setBalance(money)
}
useEffect(() => {
getBalance()
localStorage.setItem('transactionList', JSON.stringify(transactionList))
localStorage.setItem('income', JSON.stringify(income))
localStorage.setItem('expense', JSON.stringify(expense))
}, [transactionList])
const plusMinus = () => {
transaction.amount > 0
? setIncome(income + transaction.amount)
: setExpense(expense + transaction.amount)
}
const clearBudget = () => {
setTransactionList([])
setIncome(null)
setExpense(null)
alert ('Balance has been cleared')
}

Finally we will render our output….

return (<div>
<div className="container layout">
<div className="totals">
<h2 className="balance">Your Current Balance:</h2>
<h3>${balance}</h3>
<div>
<h2>History</h2>
{transactionList.map(i => {
return (
<ul key={i.description}>
<li> {i.description} {parseInt(i.amount)}</li>
</ul>
)
})}
</div>
</div>
</div>
<div className="form">
<h2 className="enter-item">Enter an Item</h2>
<form
onSubmit={e => {
e.preventDefault()
setTransactionList([transaction, ...transactionList])
plusMinus()
setTransaction({ description: '', amount: '' })
}}
>
<div>
<input
type="text"
className="input-trans"
placeholder="Enter Transaction"
value={transaction.description}
name="description"
onChange={updateForm}
/>
</div>
<input
type="number"
className="input-trans"
placeholder="Enter Amonut"
name="amount"
value={transaction.amount}
onChange={updateForm}
/>
<div className='button-container'>
<button type="submit" className="bal-sub">Submit
</button>
</div>
</form>
<div className='button-container'>
<button className="clear-sub" onClick={clearBudget}>
Clear Budget
</button>
</div>
</div>
</div>
)
}
export default App

We should end up with something like this…

and our return value…

Finally if inspect your webpage, click on Application, you can see the key and values of the localStorage that is being stored against the current browser.

Happy Coding!

--

--

Gabriel Castro

Full Stack, Software Engineer. Focus in Rails, JavaScript and React.