How to change redux state when using storybook?

Member

by dedrick , in category: Javascript , 5 months ago

How to change redux state when using storybook?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 5 months ago

@dedrick 

To change the Redux state when using Storybook, you can dispatch actions in your story to update the state. Here is an example of how you can do this:

  1. Create a decorator to provide the Redux store to your stories:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import React from 'react';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers';

const store = createStore(rootReducer);

export const withRedux = (Story) => (
  <Provider store={store}>
    <Story />
  </Provider>
);


  1. Use the withRedux decorator in your stories:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { withRedux } from './decorators';

export default {
  title: 'MyComponent',
  decorators: [withRedux],
};

export const Default = () => {
  // Dispatch an action to update the Redux state
  store.dispatch({ type: 'UPDATE_STATE', payload: { property: 'value' } });
  
  return <MyComponent />;
};


By dispatching actions in your stories, you can modify the Redux state and see the changes reflected in your components rendered by Storybook.