reactjs - React useEffect 和 Axios : Making chained API calls within 'then'

标签 reactjs promise axios react-hooks use-effect

我正在使用 NHL API 并为我的应用检索曲棍球统计数据。该 API 有多个端点,我用它们来访问玩家统计数据。

名册端点

https://statsapi.web.nhl.com/api/v1/teams/3/roster

检索此数据后,我可以访问一个名为 person 的对象,其中包含该玩家 API 端点的 ID 号,其中包含血统信息(即他们来自的国家/地区、高度/体重等)。 .)。然后,我可以发送如下所示的 API 请求,以检索该玩家的更多数据,在本例中,8476191 是 ID 号。

谱系信息端点:

https://statsapi.web.nhl.com/api/v1/people/8476191

我还可以将 ID 号 8476191 传递到包含同一玩家统计数据的统计端点。

统计端点:

https://statsapi.web.nhl.com/api/v1/people/8476191/stats?stats=statsSingleSeason&season=20182019

我想要做的是向名册端点发送请求,获取名册上每个玩家的ID号,然后对Pedigree info端点进行后续API调用 和使用 ID 号的统计端点

如何向名册端点发出 Axios get 请求,然后在调用中再嵌套两个 get 请求,以访问第一个调用中的 ID 号?这是我尝试过的:

// State for retrieving player ID numbers from roster endpoint
const [playerIDNumbers, setPlayerIDNumbers] = useState([]);

useEffect(() => {
    // Get the roster data, set playerIdNumbers to an array containing all the ID numbers
   axios.get(`https://statsapi.web.nhl.com/api/v1/teams/${teams[teamName].id}/roster`)
       .then(res => {
           setPlayerIDNumbers(Object.values(res.data.roster).map((x) => {
               return x.person.id;
           }));
           // res now contains all the ID numbers
           console.log(res);
       })
       // After grabbing all the ID numbers for each player on the roster, I want to map through each ID 
       // in the array and send a request for each player's pedigree data
       .then(res => {
           // Later in my code I created an array to contain the IDs called playerIDArr
           playerIDArr.map((playerID) => {
               axios.get(`https://statsapi.web.nhl.com/api/v1/people/${playerID}/`)
           })
           console.log('Player ID call returned : ' + res);
       })
       // After this is done I want to make a third request using the ID numbers to grab the stats /////from the stats endpoint
       /* Stats Axios request would go here */
       .catch(err => {
           console.log('Error : ' + err);
       })
}, [])

最佳答案

不需要保留状态,以下是如何使用闭包来做到这一点:

useEffect(() => {
  axios.get(`https://statsapi.web.nhl.com/api/v1/teams/${teams[teamName].id}/roster`)
    // get all ids
    .then(res => Object.values(res.data.roster).map((x) => x.person.id))
    // map through ids and retrieve the data 
    .then(ids => {
      const people = Promise.all(ids.map(id => axios.get(`https://statsapi.web.nhl.com/api/v1/people/${id}/`)))

      const stats = Promise.all(ids.map(id => axios.get(`https://statsapi.web.nhl.com/api/v1/stats/${id}/`)))

      return Promise.all([people, stats])

    }).catch(err => {
      console.log('Error : ' + err);
    })
})

// or using async/await, and some refactoring

const getRoster = id => axios.get(`https://statsapi.web.nhl.com/api/v1/teams/${id}/roster`)

const getPerson = id => axios.get(`https://statsapi.web.nhl.com/api/v1/people/${id}/`)

const getStats = id => axios.get(`https://statsapi.web.nhl.com/api/v1/stats/${id}/`)

useEffect(() => {
  const res = await getRoster(teams[teamName].id)
  const ids = Object.values(res.data.roster).map(x => x.person.id)
  return Promise.all(ids.map(id => Promise.all([getPerson(id), getStats(id)])))
})

关于reactjs - React useEffect 和 Axios : Making chained API calls within 'then' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61703393/

相关文章:

javascript - 更干净的 Promise.all 语法?

javascript - 条件渲染: comparing the result of async function in v-if

reactjs - 如何从 react 选择中仅自定义一个选项?

typescript - 使用 Fetch 和 Promise 的 Angular 2 服务

reactjs - 订阅 React 组件中的 redux 操作

javascript - 如何同步一系列 promise ?

typescript - 如何将自定义属性添加到 axios 配置?

node.js - 如何在React中查看axios错误响应JSON

javascript - 箭头函数和括号 () 或 {} 或 ({}) 的使用

javascript - bindActionCreators 在调度时调用