【问题标题】:React useEffect and Axios: Making chained API calls within 'then'React useEffect 和 Axios:在“then”中进行链式 API 调用
【发布时间】:2020-08-25 10:35:12
【问题描述】:

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

Roster endpoint

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

检索此数据后,我可以访问一个名为 person 的对象,其中包含该个人玩家的 API 端点的 ID 号,其中包含谱系信息(即他们来自的国家、身高/体重等)。然后我可以发送一个类似这样的 API 请求来检索该单个玩家的更多数据,在这种情况下,8476191 是 ID 号。

Pedigree Info endpoint:

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

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

Stats endpoint:

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

我想做的是向Roster endpoint 发送请求,获取名单上每个球员的ID 号,然后使用ID 号对Pedigree info endpointstats endpoint 进行后续API 调用.

如何向名册端点发出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);
       })
}, [])

【问题讨论】:

  • 不确定为什么要在 state 中设置玩家 ID 号码,您可以返回号码并使用下一个 .then 中的 ID 执行 Promise.all。您目前尝试使用 playerIDArr 的stale closure

标签: reactjs promise axios react-hooks use-effect


【解决方案1】:

不需要保持状态,这里是如何使用闭包做到这一点:

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)])))
})

【讨论】:

  • 两个版本都可以工作,但会以不同的方式打包结果。要等同于第一个版本,第二个版本需要是return Promise.all([ Promise.all(ids.map(getPerson)), Promise.all(ids.map(getStats)) ])(至少我认为是这样)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2021-12-28
  • 2018-02-08
  • 2022-08-18
  • 1970-01-01
相关资源
最近更新 更多