skip to Main Content

I’m trying to call simple apiCall in react js but this is giving error as given below:-

data.map is not a function

SandBox Url:-

My Code:-

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

export default function App() {
  const [data, setData] = useState();

  const apiCall = () => {
    fetch("https://fakestoreapi.com/products/1")
      .then((res) => res.json())
      .then((json) => {
        setData(json);
        console.log(data);
      });
  };

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

  return (
    <div className="App">
      {data
        ? data.map((val) => (
            <div>
              <h2>{val.id}</h2>
            </div>
          ))
        : ""}
    </div>
  );
}

Thanks for your efforts!

3

Answers


  1. Because the data return from API is an Object, and there is no map method for the object, you can use Object.entries, Object.values, Object.keys to iterate over an object.

    import "./styles.css";
    import React, { useEffect, useState } from "react";
    
    export default function App() {
      const [data, setData] = useState();
    
      const apiCall = () => {
        fetch("https://fakestoreapi.com/products/1")
          .then((res) => res.json())
          .then((json) => {
            setData(json);
          });
      };
      console.log(data);
      useEffect(() => {
        apiCall();
      }, []);
    
      return <div className="App">{
        data ? Object.entries(data).map(([key, value]) => <div><span>{ key }:</span><span>{ JSON.stringify(value) }</span></div>) : null
      }</div>;
    }
    
    

    Edit apiCall (forked)

    Login or Signup to reply.
  2. The data you’re getting from https://fakestoreapi.com/products/1 is an object, not array. You cannot only apply map method on an Object. Read about map here

    Login or Signup to reply.
  3. I edit your code to :
    you get this error because data is a object not an array

    import "./styles.css";
    import React, { useEffect, useState } from "react";
    
    export default function App() {
      const [data, setData] = useState();
    
      const apiCall = () => {
        fetch("https://fakestoreapi.com/products/1")
          .then((res) => res.json())
          .then((json) => {
            setData(json); // json is object not array
            console.log(data);
          });
      };
    
      useEffect(() => {
        apiCall();
      }, []);
    
      console.log(data);
    
      if (data) {
        return (
          <div className="App">
            <div>
              <h2>{data.id}</h2>
            </div>
          </div>
        );
      } else {
        return <></>;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search