PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] why I can't fetch product title from fakestore api?

 October 13, 2022     axios, javascript, reactjs     No comments   

Issue

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;

Solution

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>
  );
};


Answered By - Fatur Rahman
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing