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

tmikeschu

Mike Schutte

Posted on May 19, 2022

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!

💖 💪 🙅 🚩
tmikeschu
Mike Schutte

Posted on May 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related