Storybook: Loading external data before adding story

Created on 16 Feb 2017  ·  3Comments  ·  Source: storybookjs/storybook

Is it possible to do some async work like fetching of data via external API before rendering/adding a story?

Kinda like this inside:

// inside src/stories/index.js

axios.get('http://api.someURLtogetdata.com')
  .then(({ data }) => {
    storiesOf('Data Viewer', module)
      .add('Test', () => {
        return <TestStory data={data} />;
      })
});

This doesn't work. I also tried doing something like this:

const stories = storiesOf('Data Viewer', module)

axios.get('http://api.someURLtogetdata.com')
  .then(({ data }) => {
      stories.add('Test', () => {
        return <TestStory data={data} />;
      })
});

Any tips on how to achieve something like this with storybook?

Most helpful comment

Could suggest something like

class LoadData = extends React.Component {
  state = {
    data: null
  }

  componentDidMount() {
    axios.get(this.props.url).then(data => this.setState({ data }))
  }

  render() {
    return this.props.children(this.state.data)
  }
}

storiesOf('DataViewer')
  .add('test', () => (
    <LoadData url="http://api.someURLtogetdata.com">
      {data => 
        <TestStory data={data} />
      }
    </LoadData>
  ))

All 3 comments

Could suggest something like

class LoadData = extends React.Component {
  state = {
    data: null
  }

  componentDidMount() {
    axios.get(this.props.url).then(data => this.setState({ data }))
  }

  render() {
    return this.props.children(this.state.data)
  }
}

storiesOf('DataViewer')
  .add('test', () => (
    <LoadData url="http://api.someURLtogetdata.com">
      {data => 
        <TestStory data={data} />
      }
    </LoadData>
  ))

Thank you for the tip @einarlove!

This issue hints at the same problem and has a possible solution: https://github.com/storybooks/react-storybook/issues/713

What do you feel about it?

I imagine the API would look like this (this is not implemented):

storiesOf('DataViewer')
  .add('test', () => axios
    .get('http://api.someURLtogetdata.com')
    .then(({ data }) => <TestStory data={data} />)
  )

I would like to hear your feedback! If you think the solution I just posted would be fine for your usecase, let's talk about it in this issue: #713.

If you disagree and want another API, you're welcome to re-open this issue!

Was this page helpful?
0 / 5 - 0 ratings