Trying to understand useState() better

From the documentation, I am trying this to have a form with a value that can be set. Snippets:

  const [formState, setFormState] = useState( {depth: "0"});
  const onSubmit = async (formData) => {
    setFormState( formData);
<Form onSubmit={onSubmit}><TextField label="Show depth" name="depth" type="number" defaultValue={formState.depth}/></Form><Text>{formState && formState.depth}</Text>

My useState() sets the default value to β€œ0” on each render. But I would like to have the component remember what I have set from page render to page render. Submits while rendered work fine. The text below the field changes value.

What am I missing?

useState doesn’t store state permanently. You need the storage api for that. See documentation.

Change your code to something like this. It sets the initial local state from storage then updates the local state and storage when the form is submitted.

import { storage } from '@forge/api';
//...other imports

const [formState, setFormState] = useState(async ()=> await storage.get('myFormData'));
const onSubmit = async (formData) => {
    await storage.set('myFormData', formData);
1 Like

So what if two people are looking at the same page? I guess creating a storage key that consists of the page, the user, and the setting. Hmm.