storybookjs / storybook

Storybook is the industry standard workshop for building, documenting, and testing UI components in isolation
https://storybook.js.org
MIT License
83.93k stars 9.21k forks source link

[Bug]: `useParameter` API is not working on initial load. #28592

Open hwookim opened 1 month ago

hwookim commented 1 month ago

Describe the bug

The useParameter API is not working on initial load.

I'm implementing and managing a storybook-addon-cookie. My addon uses useParameter to read the cookie values entered by the user inside the story and display them in the panel.

However, since migrating to storybook version 8, when I access the parameter via useParameter, I get an empty value on initial load. When I use console.log to preview and Panel, it appears to be getting an empty value until preview is called.

Is there any way to ensure that preview.js is called before manager.js?

// Panel
export const PanelContent: React.FC = () => {
  const { path } = useStorybookState();
  const defaultCookie = useParameter<Cookie>(PARAM_KEY, {}); // TODO: Doesn't work on initial load

  const [story, setStory] = useState<string>();
  const [value, setValue] = useState<Cookie>();
  const [globals, updateGlobals] = useGlobals();

  const initCookie = () => {
    setStory(path);
    setValue(defaultCookie);
    clearCookies();
    setCookies(defaultCookie, encoding);
  };

  useEffect(() => {
    console.log('defaultCookie', defaultCookie);
    if (story !== path) {
      initCookie();
    }
  }, [defaultCookie, path, story]);
 //...
}
// preview
export const cookieDecorator = (
  storyFn: StoryFunction<Renderer>,
  { parameters }: DecoratorContext,
) => {
  const [flag, setFlag] = useState<boolean>(true);

  if (flag) {
    setFlag(false);
    if (!parameters) return storyFn();

    if (parameters[PARAM_PRESERVE_KEY] !== true) {
      clearCookies();
    }

    if (parameters[PARAM_KEY]) {
      console.log(parameters[PARAM_KEY]);
      setCookies(parameters.cookie, parameters.cookieEncoding);
    }
  }

  return storyFn();
};

스크린샷 2024-07-14 오후 5 41 57

Reproduction link

https://github.com/hwookim/storybook-addon-cookie

Reproduction steps

No response

System

The package pretty much follows the settings in addon-kit.

Additional context

No response

valentinpalkovic commented 1 month ago

@ndelangen Any ideas?

ndelangen commented 1 month ago

Is there any way to ensure that preview.js is called before manager.js?

Unfortunately, no.

This is due to the fact that parameters are dynamic, and stories are loaded async; the manager can only know about the parameters on a story, after it's been loaded.

hwookim commented 1 month ago

@ndelangen Is there any API to know if a parameter has been loaded? It's hard to know by the presence or absence of a value, since the user can send an empty value.

ndelangen commented 1 month ago

No, there's currently no way to distinguish between those scenarios.