Introduce createState which can be used in components to propagate updates
Summary:
Introduced a minimal state abstraction so that state can be maintained in the plugin instance, but subscribe to by the UI.
At a later point we could pick an off the shelve solution like Recoil or MobX, or introduce cursors to read something deep etc etc, but for now that doesn't seem to be needed at all, and I think this will be pretty comprehensible for plugin authors (see also the 25th diff in this stack).
The api
```
createState(initialValue): Atom
Atom {
get() // returns current value
set(newValue) // sets a new value
update(draft => { }) // updates a complex value using Immer behind the scenes
}
// hook, subscribes to the updates of the Atom and always returns the current value
useValue(atom)
```
Reviewed By: nikoant
Differential Revision: D22306673
fbshipit-source-id: c49f5af85ae9929187e4d8a051311a07c1b88eb5
This commit is contained in:
committed by
Facebook GitHub Bot
parent
159c0deaf1
commit
d16c6061c1
@@ -10,6 +10,7 @@
|
||||
import * as React from 'react';
|
||||
import {FlipperClient} from '../plugin/Plugin';
|
||||
import {usePlugin} from '../plugin/PluginContext';
|
||||
import {createState, useValue} from '../state/atom';
|
||||
|
||||
type Events = {
|
||||
inc: {
|
||||
@@ -25,9 +26,9 @@ export function plugin(client: FlipperClient<Events, Methods>) {
|
||||
const connectStub = jest.fn();
|
||||
const disconnectStub = jest.fn();
|
||||
const destroyStub = jest.fn();
|
||||
const state = {
|
||||
const state = createState({
|
||||
count: 0,
|
||||
};
|
||||
});
|
||||
|
||||
// TODO: add tests for sending and receiving data T68683442
|
||||
// including typescript assertions
|
||||
@@ -36,7 +37,9 @@ export function plugin(client: FlipperClient<Events, Methods>) {
|
||||
client.onDisconnect(disconnectStub);
|
||||
client.onDestroy(destroyStub);
|
||||
client.onMessage('inc', ({delta}) => {
|
||||
state.count += delta;
|
||||
state.update((draft) => {
|
||||
draft.count += delta;
|
||||
});
|
||||
});
|
||||
|
||||
function _unused_JustTypeChecks() {
|
||||
@@ -69,10 +72,11 @@ export function plugin(client: FlipperClient<Events, Methods>) {
|
||||
|
||||
export function Component() {
|
||||
const api = usePlugin(plugin);
|
||||
const count = useValue(api.state).count;
|
||||
|
||||
// @ts-expect-error
|
||||
api.bla;
|
||||
|
||||
// TODO N.b.: state updates won't be visible
|
||||
return <h1>Hi from test plugin {api.state.count}</h1>;
|
||||
return <h1>Hi from test plugin {count}</h1>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user