Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Addons: Support SSR by not using global.window to store hooks context #19631

Merged
merged 1 commit into from
Oct 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions code/lib/addons/src/hooks.test.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { useParameter, useStoryContext } from './hooks';

const { window: globalWindow } = global;

describe('addons/hooks', () => {
beforeEach(() => {
globalWindow.STORYBOOK_HOOKS_CONTEXT = undefined;
global.STORYBOOK_HOOKS_CONTEXT = undefined;
});

afterEach(() => {
globalWindow.STORYBOOK_HOOKS_CONTEXT = undefined;
global.STORYBOOK_HOOKS_CONTEXT = undefined;
});

describe('useStoryContext', () => {
Expand All @@ -21,7 +19,7 @@ describe('addons/hooks', () => {

describe('useParameter', () => {
beforeEach(() => {
globalWindow.STORYBOOK_HOOKS_CONTEXT = {
global.STORYBOOK_HOOKS_CONTEXT = {
currentContext: {
parameters: {
'undefined key': undefined,
Expand Down
10 changes: 4 additions & 6 deletions code/lib/addons/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ import {
// eslint-disable-next-line import/no-cycle
import { addons } from './index';

const { window: globalWindow } = global;

interface Hook {
name: string;
memoizedState?: any;
Expand Down Expand Up @@ -156,10 +154,10 @@ function hookify<TFramework extends AnyFramework>(fn: AbstractFunction) {
}
hooks.nextHookIndex = 0;

const prevContext = globalWindow.STORYBOOK_HOOKS_CONTEXT;
globalWindow.STORYBOOK_HOOKS_CONTEXT = hooks;
const prevContext = global.STORYBOOK_HOOKS_CONTEXT;
global.STORYBOOK_HOOKS_CONTEXT = hooks;
const result = fn(...args);
globalWindow.STORYBOOK_HOOKS_CONTEXT = prevContext;
global.STORYBOOK_HOOKS_CONTEXT = prevContext;

if (hooks.currentPhase === 'UPDATE' && hooks.getNextHook() != null) {
throw new Error(
Expand Down Expand Up @@ -218,7 +216,7 @@ const invalidHooksError = () =>
new Error('Storybook preview hooks can only be called inside decorators and story functions.');

function getHooksContextOrNull<TFramework extends AnyFramework>(): HooksContext<TFramework> | null {
return globalWindow.STORYBOOK_HOOKS_CONTEXT || null;
return global.STORYBOOK_HOOKS_CONTEXT || null;
}

function getHooksContextOrThrow<TFramework extends AnyFramework>(): HooksContext<TFramework> {
Expand Down