setPersistedForm

setPersistedForm updates a single persisted field value for a form stored in localStorage or sessionStorage without mounting the original form component.

Import

import { setPersistedForm } from '@chili'

Or, when using the namespace pattern shown across the docs, call L.setPersistedForm.

setPersistedForm({ form: string, persistence: Persistence, field: string, value: unknown, }): void

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).
fieldstringField name whose value should be updated.
valueunknownNew value that will be stored for the provided field.

The helper throws an error when no persisted form exists for the supplied key or when the stored value cannot be parsed as JSON, so make sure the form was persisted before calling it.

Example

The example below persists a form into localStorage and provides a button that updates the stored email without touching the underlying input.

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

  const updateEmail = () => {
    try {
      L.setPersistedForm({ form: formName, persistence, field: 'email', value: 'persisted@example.com' });
      alert('Persisted email updated to "persisted@example.com"');
    } catch (error) {
      alert('Persisted form not found yet. Type something in the form first.');
    }
  };

  const showPersistedData = () => {
    const data = L.getPersistedForm({ form: formName, persistence });
    alert(data ? JSON.stringify(data, null, 2) : 'No data saved 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={updateEmail}>
          Persist demo email
        </L.Button>

        <L.Button onClick={showPersistedData}>
          Show persisted data
        </L.Button>
      </div>
    </>
  );
}

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