Solution

To get json from sessionstorage in react js, use sessionStorage.getItem() method it will return JSON string then use JSON.parse() method to convert it into Object.

sessionStorage.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 sessionstorage using sessionStorage.getItem() method and then use JSON.parse() method to convert it into Object.

let user = sessionStorage.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 sessionstorage 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 objData = {
      id: 1,
      name: "John",
      work: "none of your business",
    };
    sessionStorage.setItem("user", JSON.stringify(objData));

    let user = sessionStorage.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

sessionStorage, json

codesandbox