Home > Back-end >  ReactJS taking data from API
ReactJS taking data from API

Time:03-20

  • Hello guys i don't know how to take data from API.
  • To be more specific, i have a API like this:
{
  "data": {
    "free_courses": [
      {
        "id": 7,
        "title": "Kiến Thức Nhập Môn IT",
        "slug": "lessons-for-newbie",
        "description": "Để có cái nhìn tổng quan về ngành IT - Lập trình web các bạn nên xem các videos tại khóa này trước nhé.",
        "image": "courses/7.png",
      },
    ]
  }
}
  • In reactjs, i have something like this:

    function Contact() { const [products, setProducts] = useState({});

    useEffect(() => {
      const getProducts = async () => {
        try {
          const url = "https://api-gateway.fullstack.edu.vn/api/combined-courses";
          const response = await fetch(url);
          const responseJSON = await response.json();
          setProducts(responseJSON);
          //console.log("ResponseJSON:", responseJSON);
        } catch (error) {
          console.log("Failed to fetch products: ", error);
        }
      };
      getProducts();
    }, []);
    return (
      <>
        {
          <div className="contact-container">
            {products.map((product) => (
              <ul key={product._id}>
                <h1>{product.title}</h1>
                <h2>{product.description}</h2>
              </ul>
            ))}
          </div>
        }
      </>
    );
    

    }

  • When I refresh the page and I got an error like this: Uncaught TypeError: products.map is not a function

  • I can get the //console.log("ResponseJSON:", responseJSON); and see my data from console.log but when I render it on the website and it announced an error. Thus, anyone can help me to fix my problem.

  • Thank you for all your answers.

CodePudding user response:

Make your state as an array :

const [products, setProducts] = useState([])

Also , your response from the fetch should be an array ... or , you have to save it in the form of array , so that map function works properly.

Just add a check before you render elements of a list .

<div className="contact-container">
        {products?.length&&products.map((product) => (
          <ul key={product._id}>
            <h1>{product.title}</h1>
            <h2>{product.description}</h2>
          </ul>
        ))}
      </div>

This must solve your issue .

CodePudding user response:

you should add a question mark after products, it checks if pruducts has array then map through them {products?.map((product) =>

  • Related