Added support for serialization

Summary: Make sure that DataSources can be serialized directly with a single setting, just like plain state atoms

Reviewed By: nikoant

Differential Revision: D26944954

fbshipit-source-id: 2b0d625d7d67f27a7c2e33dd7c4b534dfa4d3e82
This commit is contained in:
Michel Weststrate
2021-03-16 14:54:53 -07:00
committed by Facebook GitHub Bot
parent dd4cf9cb4a
commit 66774c90c6
12 changed files with 97 additions and 22 deletions

View File

@@ -9,7 +9,7 @@
import {produce, Draft, enableMapSet} from 'immer';
import {useState, useEffect} from 'react';
import {getCurrentPluginInstance} from '../plugin/PluginBase';
import {Persistable, registerStorageAtom} from '../plugin/PluginBase';
enableMapSet();
@@ -19,7 +19,7 @@ export type Atom<T> = {
update(recipe: (draft: Draft<T>) => void): void;
};
class AtomValue<T> implements Atom<T> {
class AtomValue<T> implements Atom<T>, Persistable {
value: T;
listeners: ((value: T) => void)[] = [];
@@ -38,6 +38,14 @@ class AtomValue<T> implements Atom<T> {
}
}
deserialize(value: T) {
this.set(value);
}
serialize() {
return this.get();
}
update(recipe: (draft: Draft<T>) => void) {
this.set(produce(this.value, recipe));
}
@@ -77,15 +85,7 @@ export function createState(
options: StateOptions = {},
): Atom<any> {
const atom = new AtomValue(initialValue);
if (getCurrentPluginInstance() && options.persist) {
const {rootStates} = getCurrentPluginInstance()!;
if (rootStates[options.persist]) {
throw new Error(
`Some other state is already persisting with key "${options.persist}"`,
);
}
rootStates[options.persist] = atom;
}
registerStorageAtom(options.persist, atom);
return atom;
}