メインコンテンツに移動

<RecoilURLSyncTransit>

Recoil Sync ライブラリ のコンポーネントで、syncEffect() または urlSyncEffect() アトムエフェクトを使用して Atom を同期する brwoser URL と同期します。

これは <RecoilURLSync> コンポーネントと同じですが、組み込みの Transit エンコーディング を備えています。

function RecoilURLSyncTransit(props: {
...RecoilURLSyncOptions,
handlers?: Array<TransitHandler<any, any>>,
}): React.Node
  • ハンドラー - カスタムクラス のハンドラからなるオプション配列。リスナーが再購読されるため、必ず安定またはメモ済みの配列インスタンスである必要があります。そうしないと、URL の変更を見逃す場合があります。

Transit エンコーディングは JSON だけを使用して行うには短すぎたり読みにくかったりしますが、MapSet JavaScript コンテナとカスタムユーザーのクラスをサポートできます。

カスタムクラス

カスタムユーザーのクラスのハンドラは handlers プロパティを使用して定義できます。

type TransitHandler<T, S> = {
tag: string;
class: Class<T>;
write: (T) => S;
read: (S) => T;
};

class ViewState {
active: boolean;
pos: [number, number];
constructor(active: boolean, pos: [number, number]) {
this.active = active;
this.pos = pos;
}
// ...
}
const viewStateChecker = custom((x) => (x instanceof ViewState ? x : null));

const HANDLERS = [
{
tag: 'VS',
class: ViewState,
write: (x) => [x.active, x.pos],
read: ([active, pos]) => new ViewState(active, pos),
},
];

function MyApp() {
return (
<RecoilRoot>
<RecoilURLSyncTransit
storeKey="transit-url"
location={{part: 'queryParams', param: 'state'}}
handlers={HANDLERS}>
{/* children */}
</RecoilURLSyncTransit>
</RecoilRoot>
);
}

const ViewState = atom<ViewState>({
key: 'ViewState',
default: new ViewState(true, [1, 2]),
effects: [syncEffect({storeKey: 'transit-url', refine: viewStateChecker})],
});