Skip to content

Commit

Permalink
✨ feat: add usePluginState hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Oct 24, 2023
1 parent 5140a7e commit f7d9460
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 6 deletions.
8 changes: 4 additions & 4 deletions src/client/fetch/pluginState.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { PluginChannel } from '../const';

export const fetchPluginState = <T = any>() =>
export const fetchPluginState = <T = any>(key: string) =>
new Promise<T>((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);
}
};

window.addEventListener('message', receiverData);

top?.postMessage({ type: PluginChannel.fetchPluginState }, '*');
top?.postMessage({ key, type: PluginChannel.fetchPluginState }, '*');
});
1 change: 1 addition & 0 deletions src/client/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './useOnStandalonePluginInit';
export * from './usePluginState';
export * from './useWatchPluginMessage';
25 changes: 25 additions & 0 deletions src/client/hooks/usePluginState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useCallback, useEffect, useState } from 'react';

import { fetchPluginState, postToUpdatePluginState } from '@/client';

export const usePluginState = <T>(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;
};
4 changes: 2 additions & 2 deletions src/client/postMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }, '*');
};

0 comments on commit f7d9460

Please sign in to comment.