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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.