How do I temporarily store form data on a user's computer from sessionstorage?

Viewed 28

I created a registration form in my solid-js application. I would like that after the submission of the form, that the values ​​entered disappear from the input fields of the form but are kept on the browser of the user temporarily (until the shutdown of the computer) in order to be able to get these values ​​later in other code files. For this, I therefore decided to use sessionstorage and wrote the following code:

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 in order to use these values ​​in other files, I do this:

    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')

because I think that since the values ​​are kept on the user's computer, it is possible to directly access the value of these variables. But the values ​​of the specified keys are not returned by sessionstorage . I looked on this stackoverflow question and also on this one but nothing. Thanks!

1 Answers

You don't have the glue code between the form field and the local storage. Here is a simple example using a signal but you can change it to use a store:

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

function App() {
  let ref: HTMLInputElement | undefined;

  const [val, setVal] = createSignal();

  const handleInput = (event: any) => {
    if (event) {
      sessionStorage.setItem('some-value', event.target.value);
    }
  };

  onMount(() => {
    const someValue = sessionStorage.getItem("some-value");
    setVal(someValue);
  });

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

render(() => <App />, document.getElementById("app")!);

We restore the stored value using onMount hook which runs after the element is mounted.

We store the new value whenever the input field is updated using onInput handler. Unlike React, Solid keeps close to HTML standards and does not use onChange.

Related