so i am writing a React application to fetch and display data and sort it according to popularity but its not working
this is the api link – https://s3.amazonaws.com/open-to-cors/assignment.json
import React, { useState, useEffect } from "react";
const App = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(
"https://s3.amazonaws.com/open-to-cors/assignment.json"
);
const print = await response.json();
const ans = Object.values(print);
const sortedProducts = ans.data.sort(
(a, b) => b.Popularity - a.Popularity
);
setProducts(ans);
// setProducts(print);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
}, []);
return (
<div>
<h1>Product List</h1>
<ul>
{products.map((product, index) => (
<li key={index}>
<strong>Title:</strong> {product.title},<strong>Price:</strong>{" "}
{product.Price},<strong>Popularity:</strong>
{product.Popularity}
</li>
))}
</ul>
</div>
);
};
export default App;
i tried to convert fetched data into object but didnt work
2
Answers
you can try this :
you can convert the object keys into an array using
Object.entries()
.after that sort the result.
also here dont use captal letter