2

Below is my code, in this I want to add code to display all the products with its image from an API, how can I do that? Please help?

import React, {useState, useEffect} from 'react'
import "bootstrap/dist/css/bootstrap.min.css"
import Axios from "axios"

function Products() {

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

const fetchProducts = async () => {
const {data} = await Axios.get('https://api.test.ts/demo/test');  
const products= data
setProducts(products);
};

useEffect(() => {

  fetchProducts()

 }, []);

 return(
     
     <div>
         Want to Display list of products from API
     </div>
 )

}

export default Products;
1
  • 1
    can you tell me what is problem? Your problem is that you dont know how to get products data and use it in Webhook? Or you dont know how to show data in JSX in React? Commented Nov 30, 2020 at 20:14

2 Answers 2

5

I tried your URL for fetching products but it is showing as not reachable so I have coded this simple app using https://jsonplaceholder.typicode.com API of the list of todos.

Hope this example helps you understand how to fetch and display items from fetched data.

import React, { useState, useEffect } from "react";
import "./styles.css";
import Axios from "axios";

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

  const fetchProducts = async () => {
    const { data } = await Axios.get(
      "https://jsonplaceholder.typicode.com/todos/"
    );
    const products = data;
    setProducts(products);
    console.log(products);
  };

  useEffect(() => {
    fetchProducts();
  }, []);

  return (
    <div>
      {products.map((product) => (
        <p key={product.id}>{product.title}</p>
      ))}
    </div>
  );
}

export default App;

CodeScandbox Link

Here is another example, where the returned data is in the form of an object instead of an array in the above Example:

import React, { useState, useEffect } from "react";
import "./styles.css";
import Axios from "axios";

const productsData = {
  note: "",
  notification: "",
  Books: [
    {
      bookID: 65342,
      img: "https://source.unsplash.com/200x300/?book",
      year: 2018,
      bookTitle: "Story Time",
      LibraryInfo: {
        Status: "Out",
        returnDate: "7 Jan"
      }
    },
    {
      bookID: 65332,
      img: "https://source.unsplash.com/200x300/?book",
      year: 2018,
      bookTitle: "Story Time",
      LibraryInfo: {
        Status: "Out",
        returnDate: "7 Jan"
      }
    }
  ]
};
export default function App() {
  const [products, setData] = useState(productsData);
  const [toggle, setToggle] = useState({});
  useEffect(() => {
    setData({});
    Axios.get("https://stylmate1.firebaseio.com/hair.json").then((response) => {
      // console.log(response.data);
      setData(productsData);
    });
  }, [toggle]);
  return (
    <div className="App">
      {/* <button onClick={() => setToggle(!toggle)}>fetch</button> */}
      {products?.["Books"]?.length &&
        products["Books"].map((product) => (
          <div key={Math.random() * 10000}>
            <img src={product.img} width="200" alt="" />
            <p>{product.bookTitle}</p>
            <p>{product.year}</p>
            <p>
              {"Library Status: " +
                product.LibraryInfo.Status +
                "\n" +
                product.LibraryInfo.returnDate}
            </p>
            <p></p>
          </div>
        ))}
    </div>
  );
}


Here is the Codesandbox Example Showing how to Render elements from JSON data returned in the form of the object instead of Array Like the above example

Sign up to request clarification or add additional context in comments.

12 Comments

You forgot to use "key" prop.
showing :- TypeError: products.map is not a function. Need to fetch from an object, so .map can work here?
you can convert Object to Array with Object.entries() and use that array to map through it
if possible, share the api url so that I can see the data it is returning, then only I can give the exact answer
or paste the data that is being returned from Axios get request
|
1
   return (
     <div>
       {products.map((product, index) => (
        <p key={index}>{product.title}</p>
       ))}
     </div>
   );
 

It's recommended to have a product id, instead of using the array index as a key prop.

   return (
     <div>
       {products.map(({ id, title }) => (
        <p key={id}>{title}</p>
       ))}
     </div>
   );

That 'key' prop helps React detect & change the modified items using their unique 'key' prop.

2 Comments

showing :- TypeError: products.map is not a function. Need to fetch from an object, so .map can work here?
that is because your 'products' variable is null, you can see that by console.loging the data variable you received after you fetched the api, try to check if you fetched correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.