DEV Community

Cover image for Leveraging the `key` prop to re-render Storybook stories
Mike Schutte
Mike Schutte

Posted on

Leveraging the `key` prop to re-render Storybook stories

I've written a fair amount about combining Storybook (SB), react-query (RQ), and Mock Service Worker (MSW) (see related posts below). I finally solved another piece of the puzzle for a better developer experience: forcing RQ queries to refetch after changing a control in SB that influences a response from MSW.

A lot of times, the stories I write only leverage controls/args to influence the result of a mock response handled by MSW. Because of this, changing controls within the story does not update the UI because no props have changed. In order to demonstrate different states, I'll write separate stories with different args configurations.

E.g.,

export type Args = ChecklistsSummaryProps & {
  isLoading: boolean;
  isEmpty: boolean;
  bigNumbers: boolean;
  avgCompletionMinutes: number;
};

// ...

const Template: SB.StoryObj<Args> = {
  render: _args => <ChecklistsSummary />,
};

export const Default: typeof Template = {
  ...Template,
};

export const Loading: typeof Template = {
  ...Template,
  args: { isLoading: true },
};

export const Empty: typeof Template = {
  ...Template,
  args: { isEmpty: true },
};

export const BigNumbers: typeof Template = {
  ...Template,
  args: { bigNumbers: true },
};
Enter fullscreen mode Exit fullscreen mode

It's a bit tedious, but ends up being very declarative and descriptive in tandem with composeStories from SB's testing-react addon.

But for cases where you want to have that nice and snappy feedback of SB controls that we know and love, you can leverage the key property on the component to force the component to refresh and run all its queries again.

const Template: SB.StoryObj<Args> = {
  render: args => <ChecklistsSummary key={JSON.stringify(args)} />,
};
Enter fullscreen mode Exit fullscreen mode

Demo!

Top comments (1)

Collapse
 
nodejsdeveloperskh profile image
node.js.developers.kh

Hi, thanks for this post. I really appreciate and encourage you to add a GitHub repo link to this post.

I also wanna know if you have a post about the different ways of writing test in storybook, things like testing interactions or applied styles? what you should test in a component vs a page, and maybe about why userEvent.hover and fireEvent.hover is not working sometimes and an addon like github.com/chromaui/storybook-addo... can do the trick.