getPersistedForm

getPersistedForm reads persisted values for a form from localStorage or sessionStorage without mounting the original form components.

Import

import { getPersistedForm } from '@chili'

or, when using the namespace pattern shown across the docs, call L.getPersistedForm.

getPersistedForm({ form: string, persistence: Persistence, field?: string, }): Record<string, unknown> | unknown | null

Parameters

ParameterTypeDescription
formstringName of the form whose values were persisted.
persistencePersistenceStorage driver that was originally used to persist the form (for example L.Persistence.localStorage or L.Persistence.sessionStorage).
fieldstringOptional field name. When provided, only that field value is returned.

The helper returns either the full form object, a field value, or null when nothing is stored for the supplied key.

Example

The snippet below persists a small form into localStorage and uses getPersistedForm to inspect the stored values.

() => {
  const formName = 'persisted-form-helper';
  const persistence = L.Persistence.localStorage;

  const showEntireForm = () => {
    const data = L.getPersistedForm({ form: formName, persistence });
    alert(data ? JSON.stringify(data, null, 2) : 'No data saved yet');
  };

  const showEmail = () => {
    const email = L.getPersistedForm({ form: formName, persistence, field: 'email' });
    alert(email != null ? email : 'Field "email" has not been stored yet');
  };

  return (
    <>
      <L.Input
        form={formName}
        name='email'
        placeholder='Email'
        persistence={persistence}
        _w-52
        _mb-4
      />

      <L.Switcher
        form={formName}
        name='newsletter'
        persistence={persistence}
        _mb-4
      >
        Subscribe to updates
      </L.Switcher>

      <div className='flex gap-4 flex-wrap'>
        <L.Button onClick={showEntireForm}>
          Show persisted form
        </L.Button>

        <L.Button onClick={showEmail}>
          Show only email field
        </L.Button>
      </div>
    </>
  );
}

Switch the persistence value to L.Persistence.sessionStorage if the form was stored in session storage instead.