1

I have stored the data returned by a form of my application on the browser from sessionStorage. However I cannot access the stored values ​​from another code file in my project and it gives me no error. I was expecting to be able to access these values ​​anywhere just by specifying the names of the variables where they were saved. Here is the code from my useSendVerificationEmail.jsx file where I declared and assigned values ​​to variables stored on my browser:

import { createStore } from "solid-js/store";
import { createSignal } from "solid-js";

const [form, setForm] = createStore({
  firstName: "",
  lastName: "",
  email: "",
  password: "",
  gender: "",
});

sessionStorage.setItem("firstName", form.firstName);
sessionStorage.setItem("lastName", form.lastName);
sessionStorage.setItem("email", form.email);
sessionStorage.setItem("password", form.password);
sessionStorage.setItem("gender", form.gender);

and here's the code from my useResendEmail.jsx file where I'm trying to access these saved values ​​and I can't:

import { createSignal } from "solid-js";

export default function useResendEmail() {
  // ... code ...

  const firstName = sessionStorage.getItem("firstName");
  const lastName = sessionStorage.getItem("lastName");
  const email = sessionStorage.getItem("email");
  const password = sessionStorage.getItem("password");
  const gender = sessionStorage.getItem("gender");

  // ... more code ...
}

I want to clarify that these constants were not declared in the file useSendVerificationEmail.jsx. I was expecting this to work and I don't understand why it is doing this. Could someone please explain my mistake to me, thanks!

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Goune Kenfack
  • 107
  • 1
  • 7

2 Answers2

1

Session storage API is used to store session related data. They are cleared once the session ends. If you are trying to access the set values from another window or tab, you may not get them.

The read-only sessionStorage property accesses a session Storage object for the current origin. sessionStorage is similar to localStorage; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.

  • Whenever a document is loaded in a particular tab in the browser, a unique page session gets created and assigned to that particular tab. That page session is valid only for that particular tab.
  • A page session lasts as long as the tab or the browser is open, and survives over page reloads and restores.
  • Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
  • Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
  • Duplicating a tab copies the tab's sessionStorage into the new tab.
  • Closing a tab/window ends the session and clears objects in sessionStorage.

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Try using local storage for storing the values.

import { render } from "solid-js/web";
import { createSignal, onMount } from "solid-js";

function App() {
  const [val, setVal] = createSignal('');

  const handleInput = (event) => {
    if (event) {
      // Update stored value when input value changes
      localStorage.setItem('some-value', event.target.value);
    }
  };

  onMount(() => {
    const storedValue = localStorage.getItem("some-value") || '';

    // Set previously stored value back upon mounting the element
    setVal(storedValue);
  });

  return (
    <div>
      <input value={val()} onInput={handleInput} />
    </div>
  );
}

render(App, document.getElementById("app"));

Logic is simple, we store the input value into local storage whenever user updates the input value. We get the stored value from the local storage when the page loads and assign it to the input value. Check the comments in code for exact locations.

Check the link for a live demo:

https://playground.solidjs.com/?hash=1883583533&version=1.4.1

snnsnn
  • 10,486
  • 4
  • 39
  • 44
0

Session storage should work between any js files if they are loaded on the same tab.

Here is a codesandbox showing so https://codesandbox.io/s/nice-forest-7g6ulz?file=/src/LoadSessionStorage.jsx:

SetSessionStorage.jsx

import { useRef } from "react";
export const SetSessionStorage = (props) => {
  const userInput = useRef(null);
  const onUserInput = () => {
    // Whenever the usre input changes, we set the new value in the sessionStorage
    sessionStorage.setItem("user", userInput.current.value);
  };
  return (
    <div>
      <div>SetSessionStorage</div>
      <input ref={userInput} type="text" onChange={onUserInput} />
    </div>
  );
};

LoadSessionStorage

import { useState, useEffect } from "react";
export const LoadSessionStorage = (props) => {
  const [user, setUser] = useState(sessionStorage.getItem("user"));
  useEffect(() => {
    // In this example we don't have any framework to notify the update of the sessionStorage
    // so we just get the value from sessionStorage every 500ms
    const id = setInterval(() => {
      setUser(sessionStorage.getItem("user"));
    }, 500);
    return () => clearInterval(id);
  }, []);
  return (
    <div>
      <div>LoadSessionStorage</div>
      <div>User: {user}</div>
    </div>
  );
};

App.jsx

import { SetSessionStorage } from "./SetSessionStorage";
import { LoadSessionStorage } from "./LoadSessionStorage";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <SetSessionStorage />
      <LoadSessionStorage />
    </div>
  );
}

In your case, I see a few possibilities (if you could provide how you set the sessionStorage and how you use useResendEmail it might help narrowing down the problem):

  • You never set the sessionStorage (or it's reset to empty not long after)
  • You set the sessionStorage, but userResendEmail is not called after the sessionStorage is updated

To check if it is the first case, in the Chrome debugger you can check in Application => Session Storage => your origin and see the current value of the SessionStorage (you might want to click on the refresh icon next to Filter to be sure to have the latest state).

In the second scenario it's likely that useResendEmail() is called in a render method (or functional component body). But since no state/props of that component changed the component is not rerendered and as such useResendEmail is not called. As you can notice in my example, because I am not using redux or anything that would notify my LoadSessionStorage that the sessionStorage was updated, I had to read the sessionStorage at regular interval to get the updates rendered.

While setInterval is definitely not the right way to fix the issue, you would need to notify the component calling useResendEmail to rerender when the sessionStorage is updated (with stores like redux, or maybe solid.js has some capabilities to signal some change from a component to another?).

user3252327
  • 617
  • 5
  • 9