Leveraging the `key` prop to re-render Storybook stories
Mike Schutte
Posted on May 19, 2022
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 },
};
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)} />,
};
Demo!
Integration stories: elevating Storybook with Mock Service Worker
Mike Schutte ・ Apr 28 '21
Posted on May 19, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.