skip to Main Content
import { useState, useEffect } from "react";
import axios from "axios";

const Aside = () => {
  const [myData, setMyData] = useState([]);

  // using Promises
  useEffect(() => {
    axios
      .get("https://dummyjson.com/products")
      .then((response) => setMyData(response.data))
  }, []);

//plz subscribe to thapa technical
  return (
    <>
      <h1>Axios Tutorial</h1>

      <div className="grid">
        {myData.map((post) => {
          const {  id, title } = post;
          return (
            <div key={id} className="card">
              <h2>{title}</h2>
            </div>
          );
        })}
      </div>
    </>
  );
};

export default Aside;

please give a solution for this error

2

Answers


  1. Your very first debugging step should be to observe the actual data you’re receiving from this URL:

    https://dummyjson.com/products
    

    When doing so, you’ll find that it’s not an array. It’s an object with the following structure:

    {
      products: [
        /...lots of objects.../
      ],
      total: 100,
      skip: 0,
      limit: 30
    }
    

    It’s an object, which has a property that is an array. If that array is what you want, set your state to that array:

    setMyData(response.data.products)
    
    Login or Signup to reply.
  2. If you look at the response, it gives a "products" array nested on the first level..
    So, you need to use myData.products.map(...).

    import { useState, useEffect } from "react";
    import axios from "axios";
    
    const Aside = () => {
      const [myData, setMyData] = useState([]);
    
      // using Promises
      useEffect(() => {
        axios
          .get("https://dummyjson.com/products")
          .then((response) => setMyData(response.data))
      }, []);
    
    //plz subscribe to thapa technical
      return (
        <>
          <h1>Axios Tutorial</h1>
    
          <div className="grid">
            {myData.products.map((post) => { /* << CHANGE HERE */
              const {  id, title } = post;
              return (
                <div key={id} className="card">
                  <h2>{title}</h2>
                </div>
              );
            })}
          </div>
        </>
      );
    };
    
    export default Aside;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search