storybook-fetch-addon
用於從 API 獲取資料的 Storybook 擴充功能
安裝
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 */ };
}
}
API
fetchSingle
(id, component, defaultValue) => Component
- id:用於識別項目的字串。
- component:將被傳遞獲取到的 props 的 React 元件。
- defaultValue:可選的字串,將用作獲取資料的預設值。
fetchList
(items, component) => Component
- items:id/defaultValue 配對的陣列。預設值為可選。
- component:將被傳遞所有項目獲取到的 props 的 React 元件。
範例
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>
)
));