Axios get waterfall way

817 views Asked by At

I have a JSON like below and need to create a data structure have user's complete profile by fetching the history and personal details from links in JSON. Any thoughts how to I do it using axios?

JSON={
      0:{
          userid:"...",
          details:"http:://<user>/profile",
          history:"http://<user>/history"
      }
      1:{
          userid:"...",
          details:"http:://<user>/profile",
          history:"http://<user>/history"
      }
      2:{
          userid:"...",
          details:"http:://<user>/profile",
          history:"http://<user>/history"
      }
    }

desired result json is

  JSON:{
    0:{
        userid:"1",
        name:"<datafrom profile>",
        age:"<data from profile>",
        last_login:"<data from history>"
    },
    1:{
        userid:"1",
        name:"<datafrom profile>",
        age:"<data from profile>",
        last_login:"<data from history>"
    },
    2:{
        userid:"2",
        name:"<datafrom profile>",
        age:"<data from profile>",
        last_login:"<data from history>"
    },
   }
1

There are 1 answers

4
Andrew Kim On

Assuming the details and history key value pairs are legit urls. I'll use http://someDataUrl.com and http://someHistoryUrl.com in this example.

Also, not really sure what your endpoints will return so I made up some examples.

function getDataInfo(user){
  return axios.get(`http://someDataUrl.com/${user}`)
}

function getHistoryInfo(user){
  return axios.get(`http://someHistoryUrl.com/${user}`)
}

let json = {}
axios.all([getDataInfo(), getHistoryInfo()])
  .then(axios.spread(function (data, history) {
    // use response from each to populate data object literal. Something like this? :
    json.name = data.name
    json.last_login = history.last_login
  }));