Solution
To get data from localstorage in react js, use localStorage.getItem()
method it will return stored value from localStorage.
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 value from localstorage using localStorage.getItem()
method.
const token = localStorage.getItem("access_token");
console.log(token); // dXNlckBleGFtcGxlLmNvbTpzZWNyZXQ=
Example
In this example, we will get token from localstorage and show in the console and page.
Let’s start coding…
import React, { useEffect, useState } from "react";
export default function App() {
const [token, setToken] = useState("");
useEffect(() => {
const token = localStorage.getItem("access_token");
console.log("token", token);
setToken(token);
}, []);
return (
<div className="App">
<h1>{`Token`}</h1>
<p>{token}</p>
</div>
);
}
Output