movpushmov / effector-reform

make & use forms without a headache
https://movpushmov.dev/effector-reform/
MIT License
19 stars 3 forks source link

[Feature Request] Add form persistence #30

Open Olovyannikov opened 1 month ago

Olovyannikov commented 1 month ago

Motivation

We all use forms. But often it happens that we fill out the form not right away, but after some time. Or we are in the metro and the connection is not stable. Or maybe we accidentally (or purposefully) reload the page. It would be nice if fields in a form were saved in such cases. For this purpose, some local storages is perfect, for example - localStorage, sessionStorage or storing certain parameters in the URL.

Examples

Effector persistence libraries

Usage

import {
  createArrayField,
  createField,
  createForm,
} from '@effector-reform/core';
import { sample, createEffect } from 'effector';
import { persist } from 'effector-storage/local';

const DEBOUNCE_TIME = 300;

const $form = createForm({
  schema: {
    name: createField('John'),
    age: 27,
  },
});

persist({
   store: $form,
   key: 'form',
   timeout: DEBOUNCE_TIME
});
movpushmov commented 1 month ago

form is a model, which can't be persistable by default. We have two possible ways to resolve this problem:

  1. Create $persisted store (or with another name), which changes form values while writing and serializing into plain object while reading
persist({
   store: form.$persisted,
   key: 'form',
});
  1. create persistForm function which has similar mechanism but in separated function.
const persistedForm = persistForm(form);

persist({
   store: persistedForm,
   key: 'form',
});