Home > Software engineering >  Displaying API With React Hooks
Displaying API With React Hooks

Time:10-17

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
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

enter image description here

CodePudding user response:

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.

  • Related