what is localStorage

localStorage allows you to store and access strings in your browser. If data that isn’t a string is stored it will convert it into a string.

localStorage does not have an expiration date.

get and set items

There are two ways to get items

localStorage.setItem(name, item) method allows you to set an item in localStorage.

JavaScript

localStorage.setItem('theme', 'dark');
localStorage.getItem('theme') // "dark"

localStorage.setItem('theme', 'light');
localStorage.theme // "light"

localStorage.setItem('favoriteFruit', 'oranges');
localStorage.favoriteFruit // "oranges"

localStorage.setItem('brian', { cool: true });
localStorage.brian // "[object Object]"
// huh ?

When storing an object into localStorage the browser will try to convert it into a string that is why we get "[object Object]".

To fix this you will have to use JSON.stringify(object) before storing into localStorage.

To access it later you would have to use JSON.parse(object).

JavaScript

const brian = {
  age: 18,
  cool: 'maybe'
}

localStorage.setItem('brian', JSON.stringify(brian));
JSON.parse(localStorage.brian);
// { age: 18, cool: "maybe" }

remove items

Items are removed by using localStorage.removeItem(item) method.

JavaScript

// storing the value yes inside the property youAreCool
localStorage.setItem('youAreCool', 'yes');

// removing the value of youAreCool from localStorage
localStorage.removeItem('youAreCool');

localStorage
  // Storage { length: 0 }

remove all items

If you want to clear localStorage you can use localStorage.clear() method.

JavaScript


// storing items into localStorage
localStorage.setItem('niceDay', true);
localStorage.setItem('age', 18);
localStorage.setItem('youAreCool', 'yes');

localStorage
  // Storage { niceDay: "true", age: "18", youAreCool: "yes", length: 3 }

localStorage.clear();

localStorage
  // Storage { length: 0 }

conclusion

localStorage allows you store data in a browser.

It can be used to persist a theme and to create an offline experience.

javascript
what is the Fibonacci Sequence

The Fibonacci Sequence is a series of numbers that starts at 0 and 1. The next number in the series is the sum of the last two numbers.

react
dynamic image source create-react-app

how to load images with different sources / url with create react app