diff --git a/src/client/fetch/pluginState.ts b/src/client/fetch/pluginState.ts index 5b6bc4b..b22e063 100644 --- a/src/client/fetch/pluginState.ts +++ b/src/client/fetch/pluginState.ts @@ -1,10 +1,10 @@ import { PluginChannel } from '../const'; -export const fetchPluginState = () => +export const fetchPluginState = (key: string) => new Promise((resolve) => { const receiverData = (e: MessageEvent) => { - if (e.data.type === PluginChannel.renderPluginState) { - resolve(e.data.props); + if (e.data.type === PluginChannel.renderPluginState && e.data.key === key) { + resolve(e.data.value); window.removeEventListener('message', receiverData); } @@ -12,5 +12,5 @@ export const fetchPluginState = () => window.addEventListener('message', receiverData); - top?.postMessage({ type: PluginChannel.fetchPluginState }, '*'); + top?.postMessage({ key, type: PluginChannel.fetchPluginState }, '*'); }); diff --git a/src/client/hooks/index.ts b/src/client/hooks/index.ts index 5cdda44..12c1760 100644 --- a/src/client/hooks/index.ts +++ b/src/client/hooks/index.ts @@ -1,2 +1,3 @@ export * from './useOnStandalonePluginInit'; +export * from './usePluginState'; export * from './useWatchPluginMessage'; diff --git a/src/client/hooks/usePluginState.ts b/src/client/hooks/usePluginState.ts new file mode 100644 index 0000000..7e17795 --- /dev/null +++ b/src/client/hooks/usePluginState.ts @@ -0,0 +1,25 @@ +import { useCallback, useEffect, useState } from 'react'; + +import { fetchPluginState, postToUpdatePluginState } from '@/client'; + +export const usePluginState = (key: string, initialValue: T) => { + const [value, setValue] = useState(initialValue); + + useEffect(() => { + fetchPluginState(key).then((e) => { + if (!e) return; + + setValue(e); + }); + }, [key]); + + const updateValue = useCallback( + (value: T) => { + setValue(value); + postToUpdatePluginState(key, value); + }, + [key], + ); + + return [value, updateValue] as const; +}; diff --git a/src/client/postMessage.ts b/src/client/postMessage.ts index a040a4a..7ece9b4 100644 --- a/src/client/postMessage.ts +++ b/src/client/postMessage.ts @@ -4,6 +4,6 @@ export const postToFillPluginContent = (content: any) => { top?.postMessage({ content, type: PluginChannel.fillStandalonePluginContent }, '*'); }; -export const postToUpdatePluginState = (state: any) => { - top?.postMessage({ state, type: PluginChannel.updatePluginState }, '*'); +export const postToUpdatePluginState = (key: string, value: any) => { + top?.postMessage({ key, type: PluginChannel.updatePluginState, value }, '*'); };