Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

javascript - Getting an API URL id from another API data not working properly

In my small react Project, I needed to use an id from one api call in subsequent api calls. I have access to the data from the first call but do not know how to use it in the second call. I tried using a string literal to access all the ids so the URL can pick each ids directly from the other API but it was just returning random IDs.

Here is my code below


import React, { Component } from "react";
import axios from "axios";
export default class Cat extends Component {
   state = {
   imagedata: [],
   data: [],
   CatWeight: "",
   CatMetric: "",

     }
   
componentDidMount(){
   this.fetchCountryData();
   this.fetchImageUrl();
}     


  fetchCountryData = async () => {
    const url = "https://api.thecatapi.com/v1/breeds";
    try {
      const response = await axios.get(url);
      const data = await response.data;
     console.log(data)
      this.setState({
        data,
      });
    } catch (error) {
      console.log(error);
    }
  };


  fetchImageUrl = async () =>{
    
    // This is the Place I'm having issue with. The line below. where imgurl becomes https://api.thecatapi.com/v1/images/search?breed_id=char as an example
    // The id is coming from the First API id's
  const imgurl = `https://api.thecatapi.com/v1/images/search?breed_id=${this.state.data.map((item) => { return item.id })} ` 

 try {
    const response = await axios.get(imgurl);
    const imagedata = await response.data;
    console.log(imagedata)
    this.setState({
        imagedata,
    });
  } catch (error) {
    console.log(error);
  }
};

   
 render() {
   return (
     <div>
      {
            this.state.imagedata.map((item, id) =>{
            return <ul key={id}>{item.id}</ul>
            })
        
      }
      
     </div>
   )
 }
}





与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I do not know that specific api, but it looks like that endpoint would only take a single id. By using map, you are giving it an array of ids. You may need to make separate api calls for each id.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...