I’m trying to retrieve data in this way:
useEffect(() => {
async function fetchData() {
const response = await fetch('https://hasanadiguzel.com.tr/api/kurgetir');
const json = await response.json();
setData(json);
}
fetchData();
}, []);
console.log(data.TCMB_AnlikKurBilgileri[0].Isim);
When I run console.log(data.TCMB_AnlikKurBilgileri);
upon opening the application, the API seems to be working fine and the data is being retrieved. However, when I try to retrieve data.TCMB_AnlikKurBilgileri[0].Isim
with console.log(data.TCMB_AnlikKurBilgileri[0].Isim);
, I get the error: ERROR TypeError: Cannot convert undefined value to object
.
But, when I save the application after running console.log(data.TCMB_AnlikKurBilgileri);
and then run console.log(data.TCMB_AnlikKurBilgileri[0].Isim);
, it works without any problems and gives the output.
How can I solve this issue? note: You can watch the video to better understand my problem https://youtu.be/x_mlvMDzUt4
2
Answers
You are trying to assign an object to an array.
data
is array andjson
is an object.Instead of empty array use
null
as default value:In order to track data changes you should also add a separate useEffect
You are trying to console.log outside of useEffect. It cause the problem since your api did not fetch data yet, but you are trying to log data.
So, move your console.log inside of useEffect to check api response is correct.
At first when you render the component, data has no any value(so maybe undefined) if you did not set initial value. Once api request done and updated state with response, your UI will updated with correct value.