apgujeong
apgujeong

Reputation: 99

React Route Fetch Multiple URLs

I have a route that fetches JSON data from an API and res.send it to my webpage component.

app.get('/search-data', (req, res) => {

    fetch(url)
    .then(res => res.json())
    .then(data => { 
       res.send({ data });
    })
    .catch(err => {
       res.redirect('/error')
    })

I want to make multiple fetch requests. I think I need to use Promise.all but how do I format it?

My component receives one data array:

async componentDidMount() {    
   const response = await fetch('/search-data');
   const res = await response.json();
   ...

Upvotes: 2

Views: 570

Answers (1)

willman
willman

Reputation: 1211

If you want to fetch and parse multiple URLs, then send all the results in a single array, this should do it:

   app.get('/search-data', (req, res) => {
        let myfetches = [];

        myfetches.push(fetch(url1).then(res => res.json()));
        myfetches.push(fetch(url2).then(res => res.json()));
        myfetches.push(fetch(url3).then(res => res.json()));

        Promise.all(myfetches)
        .then(datas => { 
           res.send({ datas });
        })
        .catch(err => {
           res.redirect('/error')
        })

Upvotes: 3

Related Questions