DEV Community

Discussion on: How to make many http requests with react

Collapse
 
mikkpr profile image
Mikk Pristavka • Edited

Maybe it's not about the requests, but how you expect to use the responses. The React.Component's setState method is asynchronous, so you can't expect the component's state to have both work and otherWorks every time render() is called.
As Leighton suggested, Promise.all would help you make only one setState call, but it still doesn't cover the case right after mounting the component when neither of the values are present in the state.
Maybe consider adding a loading flag in the state that is set to false when both requests have completed, so render() can show a loading animation while the requests are still waiting for responses.

class MyComp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      work: undefined,
      otherWorks: undefined
    };
  }
  componentDidMount = () => {
    const { match: { params } } = this.props
    const fetchWork = fetch(`/w/${params.work}`)
    const fetchOtherWorks = fetch('/works')

    Promise.all([fetchWork, fetchOtherWorks])
      .then(([work, otherWorks]) => {
        this.setState({
          loading: false,
          work,
          otherWorks
        });
      })
      .catch(error => {
        // handle errors
      })
  }

  render() {
    const {loading, work, otherWorks} = this.state;
    if (loading) {
      return <div>Still loading!</div>
    } else {
       return (
         // whatever you want to do with `work` and `otherWorks`
       );
    }
  }  
}