Skip to content

[Bug]: Error "Storybook preview hooks..." in setState() #22132

Open

Description

Describe the bug

If you have controlled component and need to use React state in story file to control component's state you may have the template like this one:

// Component.stories.js
const Template = {
  render: function Render(args) {
    const [args_, setArgs] = useArgs()
    const [value, setValue] = useState()
    useEffect(() => {
      args.value = value
    }, [value])

    const onChange = (value) => {
      action('onChange')(value)
      setArgs({ value: value })
      // error executing this line if there is decorator with <Story /> in preview.js
      setValue(value)
    }

    return <InputField {...args} onChange={onChange} />
  },
  args: {
    value: '',
  },
}

In my case it generated error:

Storybook preview hooks can only be called inside decorators and story functions. 

I couldn't peroduce it in Stackblitz sandbox. It appeared that it reproduces for decorators with JSX variant of Story in my preview.js file, for example:

  // preview.js
  (Story) => (
    <>
      <GlobalStyle />
      <Story />
    </>
  ),

This applies to any imported decorator too.
When I changed Story to function, error went away:

  (Story) => (
    <>
      <GlobalStyle />
      {Story()}
    </>
  ),

Similar case was mentioned in some comments but I cannot find it.

To Reproduce

https://stackblitz.com/edit/github-uixpen-fdysyn?file=.storybook%2Fpreview.js,src%2Fstories%2FInputField.stories.js)

System

Storybook 7, any system.

Additional context

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions