Solution
To get json from localstorage in react js, use localStorage.getItem()
method it will return JSON string
then use JSON.parse()
method to convert it into Object
.
localStorage.getItem()
The getItem()
method of the Storage interface
, when passed a key name, will return that key’s value, or null
if the key does not exist, in the given Storage object.
Snippet
In this snippet, we will get some JSON value from localstorage using localStorage.getItem()
method and then use JSON.parse()
method to convert it into Object
.
let user = localStorage.getItem("user");
console.log(user); // '{"id":1,"name":"John","isAlive":"Of course"}'
user = JSON.parse(user)
console.log(user); // {id: 1, name: 'John', isAlive: 'Of course'}
Example
In this example, we will get json from localstorage and show in the console and page.
Let’s start coding…
import React, { useEffect, useState } from "react";
export default function App() {
const [user, setUser] = useState(null);
useEffect(() => {
let user = localStorage.getItem("user");
console.log(user);
user = JSON.parse(user)
console.log(user);
setUser(user);
}, []);
return (
<div className="App">
<h1>{`User Name`}</h1>
<p>{user?.name}</p>
</div>
);
}
Output