Skip to content

Commit

Permalink
Merge pull request #30259 from storybookjs/jeppe/fix-infinite-render
Browse files Browse the repository at this point in the history
Manager API: Fix infinite render-loop caused by `useSharedState`
  • Loading branch information
valentinpalkovic authored Jan 14, 2025
2 parents af73cba + 80a3be2 commit e20811a
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions code/core/src/manager-api/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -400,13 +400,17 @@ export function useSharedState<S>(stateId: string, defaultState?: S) {
}
}, [quicksync]);

const setState = async (s: S | API_StateMerger<S>, options?: Options) => {
await api.setAddonState<S>(stateId, s, options);
const result = api.getAddonState(stateId);
const setState = useCallback(
async (s: S | API_StateMerger<S>, options?: Options) => {
await api.setAddonState<S>(stateId, s, options);
const result = api.getAddonState(stateId);

STORYBOOK_ADDON_STATE[stateId] = result;
return result;
},
[api, stateId]
);

STORYBOOK_ADDON_STATE[stateId] = result;
return result;
};
const allListeners = useMemo(() => {
const stateChangeHandlers = {
[`${SHARED_STATE_CHANGED}-client-${stateId}`]: setState,
Expand Down Expand Up @@ -446,14 +450,20 @@ export function useSharedState<S>(stateId: string, defaultState?: S) {
}, [stateId]);

const emit = useChannel(allListeners);
return [
state,

const stateSetter = useCallback(
async (newStateOrMerger: S | API_StateMerger<S>, options?: Options) => {
await setState(newStateOrMerger, options);
const result = api.getAddonState(stateId);
emit(`${SHARED_STATE_CHANGED}-manager-${stateId}`, result);
},
] as [S, (newStateOrMerger: S | API_StateMerger<S>, options?: Options) => void];
[api, emit, setState, stateId]
);

return [state, stateSetter] as [
S,
(newStateOrMerger: S | API_StateMerger<S>, options?: Options) => void,
];
}

export function useAddonState<S>(addonId: string, defaultState?: S) {
Expand Down

0 comments on commit e20811a

Please sign in to comment.