Storybook: are there any good examples out there how to reset state when switching stories? #5208
Replies: 2 comments 9 replies
-
|
Perhaps I need to pass over the I'm unsure. Feels like overcomplicated and too much boilerplate. Because when configuring a new store based on reducers AND when there is no preloadedState, it should always point back to the initial state all reducers come from, don't you think so? |
Beta Was this translation helpful? Give feedback.
-
|
just like with tests, your stories should get a fresh store, not a shared singleton. here's what i do: // store.ts
const rootReducer = combineReducers({ ... })
export type PreloadedState = Parameters<typeof rootReducer>[0]
export function makeStore(preloadedState?: PreloadedState) {
return configureStore({
reducer: rootReducer,
...
})
}
export type AppStore = ReturnType<typeof makeStore>
export type RootState = ReturnType<AppStore["getState"]>
export type AppDispatch = AppStore["dispatch"]
// .storybook/preview.ts
import type { Decorator, Preview } from "@storybook/react-vite";
import { Provider } from "react-redux"
import { type PreloadedState, type AppStore, makeStore } from "../store"
declare module "@storybook/react" {
export interface Parameters {
preloadedState?: PreloadedState;
store?: AppStore
}
}
export const reduxDecorator: Decorator = (Story, { parameters }) => {
parameters.store ??= makeStore(parameters.preloadedState)
return (
<Provider store={parameters.store}>
<Story />
</Provider>
);
}then if you want to preload some state/provide a store, you can: const ExampleStory: Story = {
parameters: {
preloadedState: { counter: { value: 2 } }
}
}
// or
const store = makeStore();
store.dispatch(increment())
const ExampleStory: Story = {
parameters: { store }
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello folks,
I wonder if there are any good react-redux/RTK examples out there using Storybook?
Storybook is great for testing UI components in isolation.
My problem is, when I switch between stories, it still uses the previous state. Similar to unit tests, I'd like to reset it back to initial state. Yet, it still uses the previous state.
For example, one single boolean: enable or disable audio, see screenshot where it's wrong:
When switching from without audio (= false) to with audio, it should reload the initial state where audio is enabled, but it doesn't.
I've set up a storybook decorator to fix this, but it doesn't work properly, see:
https://github.com/binarykitchen/videomail-recorder/blob/main/.storybook/preview.tsx#L45
So yes, that's why I am asking around for good examples how to reset back to the initial state whenever you switch a story within Storybook.
Thanks for any pointers or advice :)
Beta Was this translation helpful? Give feedback.
All reactions