Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

data.map is not a function in react all api

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:-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading