简体   繁体   中英

Displaying API With React Hooks

I am trying to display a list of facts from this cat fact API https://catfact.ninja/facts?limit=15 .

I have fetch the data and see the facts, 0-14, displayed in console. I created a map() to iterate through the array but only the first fact will display on the list. Thank you for your help!

 import React, { useState, useEffect } from 'react'; const url = 'https://catfact.ninja/facts?limit=15'; const Index = () => { const [factList, setFactList] = useState([]); useEffect(() => { getList() },[]); const getList = () => { fetch(url) .then((res) => res.json()) .then((list) => { console.log('List:', list); const [factList] = list.data setFactList([factList]) }) .catch((err) => { console.log('List ERROR ', err); }) } return ( <div className='App'> <h1>FACT LIST</h1> <ul> {factList.map((item, index) => <li key={index}> {item.fact} </li> )} </ul> </div> ) } export default Index

enter image description here

Change your fetch function to this:

const getList = () => {
  fetch(url)
    .then((res) => res.json())
    .then((list) => {
      setFactList(list.data);
    })
    .catch((err) => {
      console.log("List ERROR ", err);
    });
};

const [factList] = list.data; causes that only first element of the array is assigned to the factList . Read more about destructuring in JS.

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