DEV Community

Cover image for Database in JavaScript (Local Storage)
Jack Pritom Soren
Jack Pritom Soren

Posted on

Database in JavaScript (Local Storage)

Local Storage:

Local Storage is an API provided by browsers that allows you to create, read, update and delete records in the browser. These records are limited to the browser only, meaning data stored in chrome is not available on firefox and vice versa

Before We start
The local storage data is in JSON format, which means when storing the data, we need to convert the JavaScript Object to a JSON format and vice versa.

const person={
    name: "Jack Pritom Soren"
}

const personToJson = JSON.stringify(person)
Enter fullscreen mode Exit fullscreen mode

Visual View

  • Open Developer tools

  • Go to Application tab

  • Select Local Storage

Local Storage

Create New Record:

const person={
    name: "Jack Pritom Soren"
}

const personToJson = JSON.stringify(person)

localStorage.setItem("person",personToJson)
Enter fullscreen mode Exit fullscreen mode

Read a Record:

const personToJson = localStorage.getItem("person")

const JsonToPerson = JSON.parse(personToJson)

console.log(JsonToPerson)
Enter fullscreen mode Exit fullscreen mode

Update a Record:

const person={
    name: "Jack Pritom Soren",
    country: "Bangladesh"
}

const personToJson = JSON.stringify(person)

localStorage.setItem("person",personToJson)
Enter fullscreen mode Exit fullscreen mode

Delete a Record:

localStorage.removeItem("person")
Enter fullscreen mode Exit fullscreen mode

Follow me on : Github Linkedin

Top comments (2)

Collapse
 
theaccordance profile image
Joe Mainwaring • Edited

I would recommend caution with using LocalStorage, while yes - you can absolutely do everything you've described, it's a volatile storage space and there are known instances where an Operating System or Browser ran out of memory and recycled space used by LocalStorage, corrupting the data that was previously set.

I encountered this with a PWA a few years ago, Android would recycle the space where I had a token stored and then calls to the server wouldn't work.

Bugs aside though - sharing this knowledge is still beneficial and I hope you continue to do so 😎

Collapse
 
pubkey profile image
Daniel M

Localstorage is ok to use for key-value data. But as soon as you store more complex documents, you should switch to an async storage like IndexedDB or RxDB