简体   繁体   中英

How to fetch only the first data from an API in React?

I am currently working on a website that, when I open it, should always print a random quote from the API. However, when I open the API, it doesn't randomly display a quote in json format, but outputs all the quotes stored in an array. My problem is that on my website all the quotes are spinning until the debugger stops for lack of memory. How can I make the map function display only the first data of the array? My code:

const randomIndex = (arr) => {
    // returns a random int value to use as an index
    return Math.floor(Math.random() * arr.length);
  };

  const [quote, setQuote] = useState("");
  const [index, setIndex] = useState(0);

  const QuoteAPI = async () => {
    let arrayOfQuotes = [];
    const data = await axios.get("https://type.fit/api/quotes");
    arrayOfQuotes = data.data;
    console.log(arrayOfQuotes);
    const quote = arrayOfQuotes.map((arrayOfQuote) => (
      <div key={arrayOfQuote.id}>
        <h3>{arrayOfQuote.text}</h3>
        <p>{arrayOfQuote.author}</p>
      </div>
    ));
    console.log(quote);
    setQuote(quote);
  };

  useEffect(() => {
    QuoteAPI();
    setIndex(randomIndex(quote));
  }, [quote]);

You don't need to use the map() method as it returns an array not a single object. All you need is to get the first item in the returned array, then format and display it. Something like this:

     let arrayOfQuotes = [];

        const data = await axios.get("https://type.fit/api/quotes");

        arrayOfQuotes = data.data;

        if(arrayOfQuotes.length > 0){
           const quote = (
              <div key={arrayOfQuotes[0].id}>
                 <h3>{arrayOfQuotes[0].text}</h3>
                 <p>{arrayOfQuotes[0].author}</p>
              </div>);
          setQuote(quote);
       }

By the way, the API endpoint you are using returns a list while you need a single quote. I think there should be another endpoint which provides a single quote. You need to check the API documents if it has one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM