Storybook addon for fetching data from api
npm i --save-dev storybook-fetch-addon
// In addons.js
import 'storybook-fetch-addon/register';
// In config.js
import { addDecorator, addParameters } from '@storybook/react';
import { withFetch } from 'storybook-fetch-addon';
addDecorator(withFetch);
addParameters({
fetch: {
// Required:
fetch: param => fetch(`https://my-api.com?id=${param}`),
// Optional:
map: data => {
// transform data from api
return props;
},
valid: value => {
// Validate value
return valid;
},
defaultProps: {
return { /* default props */ };
}
}
(id, component, defaultValue) => Component
- id: string that identifies the item.
- component: React component that will be passed the fetched props.
- defaultValue: optional string that will be used as default value for fetching data.
(items, component) => Component
- items: array of id/defaultValue pairs. Default value is optional.
- component: React component that will be passed the fetched props for all items.
import { fetchSingle, fetchList } from 'storybook-fetch-addon';
storiesOf('My Component')
.add('single', () => fetchSingle(
'Item 1',
({ props, loaded, error }) => <MyComponent {...props} />,
'default value'
))
.add('list', () => fetchList(
[
['Item 1', 'default 1'],
['Item 2', 'default 2']
],
({ items }) => (
<ul>
{items.map(({ props, loaded, error }) => <MyComponent key={props.id} {...props} />)}
</ul>
)
));