useFormStorage

Hook to create a form where changes will be saved in a storage.


Hook to create a form where changes will be saved in a storage.
Note: that when changes are done to form data, it’s always better to change/update the version so storage data is cleared.
Note: By default it will clear the form from storage when submitted with success.

FormStorage Options

// object
const { ... } = useFormStorage(
  ...,
  {
	//... same as normal useForm

	// Required
	uniqueId: 'unique form id', // Mandatory so you can save multiple forms
	storage: {
	  getItem: (key) => 'return key or null',
	  removeItem: (key) => {},
	  setItem: (key, value: string) => {}
	}
	// Or storage: window.localStorage

	// NotRequired
	autoSyncWithStorage: true,
	shouldClearAfterSubmit: true,
	version: '1.0.0',
	onLoading: (isLoading) => {},
	onStorageError: (error) => {}
  }
)
NameTypeRequiredDefaultDescription
uniqueIdstringtrueundefinedUnique id for storage
storage{ getItem: (key) => 'return key or null', removeItem: (key) => {}, setItem: (key, value: string) => {} }trueundefinedStorage where form is going to be saved
autoSyncWithStoragebooleanfalsetrueWhen true, will automatically sync the form data with storage one
shouldClearAfterSubmitbooleanfalsetrueShould clear storage after submit
versionstringfalse1.0.0Storage version (changing will clear form from storage)
onLoading(isLoading) => voidfalseundefinedReading from storage can be a small delay, onLoading serves to show a loading.
onStorageError(error) => voidfalseundefinedIn case reading or writing in storage gives an error

Class vs JSON

When using useFormStorage all data will be converted to JSON (localStorage, indexDB, etc only work with pure JSON) that means Class’s prototype will be removed. To prevent this from occurring some class decorators/functions are provided.

PreserveClass or addClassToPreserve

With Decorator:

@PreserveClass
class Test {
  public doSomething() {
  
  }
}

@PreserveClass
class AppTest {
  public test = {
	subTest: 1
  };

  public classTest1 = new Test();

  public classArrayTest = []

  public classTest2?: Test;
}

With a simple function:

class Test {
  public doSomething() {

  }
}
addClassToPreserve(Test)
class AppTest {
  public test = {
  	subTest: 1
  };

  public classTest1 = new Test();

  public classArrayTest = []

  public classTest2?: Test;
}
addClassToPreserve(AppTest)