Leroi
Leroi

Reputation: 369

How to display product info from an array in react?

I would like to render a div block for each product name in an array. I am getting a list of products from an api which contains product name and cost. The following piece of code works if i try to list the elements but I would like to put these products in a preexisting div block i created.

function Basket() {
    
     const[prods, setProds] = useState([])
    

     function refreshList(){
         
            fetch("http://localhost:60036/api/Product")
            .then(response=>response.json())
            .then(data => {
                console.log(data)
                setProds(data);
            })
        }
        
    useEffect(() => {
        refreshList()
    }, []);

return (
    <>  
    <div>
       <ul>
           {
               prods.map(prod => <li> {prod.ProductName}</li>)
           }
        </ul>
    </div>
    </>
)
}

export default Basket;

The above works well and prints the product name and id. However, I want a basket-product to be created for each product name in the list returned from the call in the following div block which I want to insert in the return. I have some static product names now.

<div className="basket">
    <div className="basket-product">
        <div className="item">
            <div className="product-image">
                <img src="http://placehold.it/120x166" alt="Placholder Image 2" className="product-frame" />
            </div>
            <div className="product-details">
                <h1>
                    <strong><span className="item-quantity">4</span> x Eliza J</strong> Lace Sleeve Cuff Dress
                </h1>
                <p><strong>Navy, Size 18</strong></p>
                <p>Product Code - 232321939</p>
            </div>
        </div>
        <div className="price">26.00</div>
        <div className="quantity">
            <input type="number" defaultValue="{4}" min="{1}" className="quantity-field" />
        </div>
        <div className="subtotal">104.00</div>
        <div className="remove">
            <button>Remove</button>
        </div>
    </div>
</div>

Upvotes: 1

Views: 1454

Answers (2)

brijesh-pant
brijesh-pant

Reputation: 1145

// To answer: If you look in the div block in the second part of the question there is a defaultValue="{4}". I am getting the product information now from an api. I will like to increment the default value by 1 if we have thesame item twice from the fetched data.

In that case, you need to filter the list of data you get from the response, something like a code I've shared below. When filtering the data you can change the defaultValue to new value by increment/decrement it. An example

https://codesandbox.io/s/tender-hamilton-w5plf?file=/src/App.js

const data = [
  { id: 1, name: "Noodles" },
  { id: 2, name: "Pasta" },
  { id: 1, name: "Noodles" }
];

export default function App() {
  const [prods, setProds] = React.useState([]);

  function refreshList() {
    // filter here the response data you get from the API before setting it to component state
    const filteredData = data.reduce((acc, curr) => {
      if (acc.some(({ id }) => id === curr.id)) {
        return acc;
      }
      acc.push(curr);
      return acc;
    }, []);
    setProds(filteredData);
  }

  React.useEffect(() => {
    refreshList();
  }, []);

  return (
    <>
      <div>
        <ul>
          {prods.map(prod => (
            <li> {prod.name}</li>
          ))}
        </ul>
      </div>
    </>
  );
}

Upvotes: 0

brijesh-pant
brijesh-pant

Reputation: 1145

You can update return statement like this

return (
  <div className="basket">
    {prods.map(prod => (
      <div key={prod.id} className="basket-product">
        {prod.ProductName} // here you can add the other jsx code aswell
      </div>
    ))}
  </div>
);

Upvotes: 2

Related Questions