Home > Blockchain >  React Native 'ERROR TypeError: Cannot convert undefined value to object'
React Native 'ERROR TypeError: Cannot convert undefined value to object'

Time:12-23

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

CodePudding user response:

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.

const json = await response.json();
console.log(json.TCMB_AnlikKurBilgileri[0].Isim);
setData(json);

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.

CodePudding user response:

You are trying to assign an object to an array. data is array and json is an object.

Instead of empty array use null as default value:

const [data, setData] = useState(null)

In order to track data changes you should also add a separate useEffect

useEffect(() => {
 console.log(data?.TCMB_AnlikKurBilgileri[0]?.Isim)
},[data])
  • Related