skip to Main Content

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


  1. you can try this :

    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.sort(
              (a, b) => b.Popularity - a.Popularity
            );
            setProducts(sortedProducts);
          } 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;
    
    Login or Signup to reply.
  2. you can convert the object keys into an array using Object.entries().
    after that sort the result.

    import { useState, useEffect } from 'react';
    
    export 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 productArray = Object.entries(print.products).map(([id, product]) => ({
              id,
              ...product
            }));
            
    
            const sortedProducts = productArray.sort((a, b) => b.popularity - a.popularity);
            setProducts(sortedProducts);
            
          } 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>
      );
    };
    

    also here dont use captal letter

    <li key={index}>
                <strong>Title:</strong> {product.title},<strong>Price:</strong>{" "}
                {product.Price},<strong>Popularity:</strong>
                {product.Popularity}
              </li>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search