How to make many http requests with react

Hi, please i'm stuck.
is somebody knows how to make many request in a react component or route?

componentDidMount = () => {
    const { match: { params } } = this.props
    fetch(`/w/${params.work}`)
      .then(res => res.json())
      .then(work => this.setState({ work }))

    fetch('/works')
      .then(res => res.json())
      .then(otherWorks => this.setState({ otherWorks }))
}

something like this that works.
I'm a beginner with React so i don't really want things like Redux
i just want a beginner way.The first fetch work but not the second

Did you find this post useful? Show some love!

I think promise.all() is going to be what you're looking for.

const firstFetch = fetch('some/resource')
const secondFetch = fetch('some/other/resource')

Promise.all([firstFetch, secondFetch])
  .then(values => {
    // do something with values
    // values[0] is the result of firstFetch
    // values[1] is the result of secondFetch
  })
  .catch(error => {
    // handle any errors
  })

if you have multiple callback asynchrous update the setState, you should consider this method to make sure they don't overwrite each other or race conditions:

this.setState( prevState => ({ ...prevState, work1: result });

this.setState( prevState => ({ ...prevState, work2: result });

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`
       );
    }
  }  
}
Ben Halpern DEV.TO FOUNDER

Hey there, we see you aren't signed in. (Yes you, the reader. This is a fake comment.)

Please consider creating an account on dev.to. It literally takes a few seconds and we'd appreciate the support so much. ❀️

Plus, no fake comments when you're signed in. πŸ™ƒ

Guys i'm sorry.It was a {} I'd forgotten somewhere really sorry.
And thanks for your answers i think it'll save my life in few days

Your code is making two requests at once - what isn't working about it exactly?

i'm supposed to receive an array of data in the otherWorks but i got an empty array

Classic DEV Post from May 7

Who's looking for open source contributors? (May 7 edition)

Please shamelessly promote your project. Everyone who posted in previous weeks ...

READ POST
Follow @ben to see more of their posts in your feed.
dev.to is now open source!
View Announcement Post View GitHub Repo
Kael_
UI/UX Designer and Frontend self-taught developer who loves Mangas&Animes, mythologies.
More from @iamkael
React, React-Router and Fetch API
#react #help #beginners #fetchapi
How do you handle a component update ?
#react #beginners #help #javascript
Trending on dev.to
Which functional language would you recommend for a web app (SPA)?
#help #functional
Blockchain based dApp for Donation System
#blockchain #ethereum #soldity #react
React Component Lifecycle Explained
#react #javascript #webdev #beginners
Learning Redux and notes
#javascript #react #redux
The distraction's killer
#beginners #help #career
React Weather App Video Course 12-14
#javascript #react
How to code split Redux store to further improve your app's performance
#react #redux #javascript #performance
Leaving the Old Ways - jQuery vs React
#javascript #react #jquery #softwaredevelopment