Solution

To store an object in sessionstorage in react js, use sessionStorage.setItem() with the JSON.stringify() method it will convert an object into a string and store it in sessionstorage.

sessionStorage.setItem()

The setItem() method of the Storage interface, when passed a key name and value, will add that key to the given Storage object, or update that key’s value if it already exists.

JSON.stringify()

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Snippet

In this snippet, we will store JSON objects in local storage using sessionStorage.setItem() with the JSON.stringify() method.

let obj = {
  id: 1,
  name: "John",
  work: "none of your business",
};

// store object in local storage
sessionStorage.setItem("obj", JSON.stringify(obj));

// Get object from local storage
obj = sessionStorage.getItem("obj");
if (obj) {
  obj = JSON.parse(obj);
  console.log(obj); // {id: 1, name: 'John', work: 'none of your business}
}

Example

In this example, we will create an object and store it sessionstorage after storing we will get an object from sessionstorage and show it in the UI.

Let’s start coding…

import React, { useEffect, useState } from "react";
export default function App() {
  const [obj, setObj] = useState([]);

  useEffect(() => {
    storeSessionstorage();

    fetchSessionstorage();
  }, []);

  const storeSessionstorage = () => {
    let objData = {
      id: 1,
      name: "John",
      work: "none of your business",
    };
    sessionStorage.setItem("obj", JSON.stringify(objData));
  };

  const fetchSessionstorage = () => {
    let obj = sessionStorage.getItem("obj");
    if (obj) {
      obj = JSON.parse(obj);
      setObj(obj);
    }
  };

  return (
    <div className="App">
      <h1>{`Object From Sessionstorage`}</h1>
      <p>{obj.name}</p>
    </div>
  );
}

Output

sessionStorage, Object

codesandbox