-1

I want to fetch product title from fakestoreapi . but why product title shows undefined in console. Here is my code -

import React, { useEffect, useState } from "react";
import axios from "axios";
const Ari = () => {
  const [name, setName] = useState([]);
  useEffect(() => {
    async function getData() {
      const res = await axios.get(

          "https://fakestoreapi.com/products"
      );
      setName(res);
        console.log(res.data.title);
    }
    getData();
  }, []);
  return <>

<h1>nothing to show now</h1>

  </>;
};

export default Ari;
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Arijit das
  • 69
  • 8
  • 1
    The API responds with an array. Perhaps you meant `setName(res.data)` since `res` is the full [Axios Response](https://axios-http.com/docs/res_schema). If you want to log the first title, try `res.data[0].title` – Phil Jul 26 '22 at 01:07
  • thanks for the response. Now I got it – Arijit das Jul 26 '22 at 02:15

1 Answers1

4

if you get api from axios you will receive a data of array. and you must access with console.log(res.data[indexOfArrayData].title).

see this code for resolve your problem.

const GetDataAxios = () => {
  const [data, setData] = useState([]);
  useEffect(() => {
    getData();
  }, []);
  const getData = async () => {
    const res = await axios.get("https://fakestoreapi.com/products");
    setData(res.data);
    console.log(res.data[1].title)
  };
  return (
    <div>
      {data &&
        data.map((item, i) => (
          <div key={i}>
            <p>{item.title}</p>
          </div>
        ))}
    </div>
  );
};