简体   繁体   中英

I can't access JSON Object values

Had these response below from server in console. However, i can't seem to access data[0].type or data[1].count. It's giving me this error TypeError: Cannot read properties of undefined (reading 'type') .

 (5)[{…}, {…}, {…}, {…}, {…}] 0: { type: 'hotel', count: 7 } 1: { type: 'apartments', count: 0 } 2: { type: 'resorts', count: 0 } 3: { type: 'villas', count: 0 } 4: { type: 'cabins', count: 0 } length: 5

Below is the function to get data from server using axios

 const useFetch = (url) => { const [data,setData] = useState([]); const [loading,setLoading] = useState(false); const [error,setError] = useState(false); useEffect(() => { const fetchData = async () => { setLoading(true); try{ await axios.get(url).then((res) => { setData(res.data); }) }catch(err){ setError(err); } setLoading(false); }; fetchData(); }, [url]); const reFetch = async() => { setLoading(true); try{ const res = await axios.get(url); setData(res.data); }catch(err){ setError(err); } setLoading(false); }; return {data,loading,error,reFetch}; }; export default useFetch;

if i try console.log(data[0]), it gives me the an object. But if i try console.log(data[0].type), it doesn't

 import "./propertyList.css"; import useFetch from '../../hooks/useFetch' import React from 'react'; const PropertyList = () => { const { data, error, loading } = useFetch("/hotels/countByType") const images = [ "https://cf.bstatic.com/xdata/images/xphoto/square300/57584488.webp?k=bf724e4e9b9b75480bbe7fc675460a089ba6414fe4693b83ea3fdd8e938832a6&o=", "https://cf.bstatic.com/static/img/theme-index/carousel_320x240/card-image-apartments_300/9f60235dc09a3ac3f0a93adbc901c61ecd1ce72e.jpg", "https://cf.bstatic.com/static/img/theme-index/carousel_320x240/bg_resorts/6f87c6143fbd51a0bb5d15ca3b9cf84211ab0884.jpg", "https://cf.bstatic.com/static/img/theme-index/carousel_320x240/card-image-villas_300/dd0d7f8202676306a661aa4f0cf1ffab31286211.jpg", "https://cf.bstatic.com/static/img/theme-index/carousel_320x240/card-image-chalet_300/8ee014fcc493cb3334e25893a1dee8c6d36ed0ba.jpg" ] console.log(data[0].type); return ( < div className = "pList" > { loading? ( "Loading" ): ( < > { data && images.map((img, i) => ( < div className = "pListItem" > < img src = { img } alt = "" className = "pListImg" / > < div className = "pListTitles" > { /* <h1>{data[i]?.type}</h1> <h2>{data[i]?.count} {data[i]?.type} </h2> */ } < /div> < /div> )) } < /> ) } < /div> ); }; export default PropertyList;

Possible two reasons for this are:

  1. request end's up as error and "data" is undefined

  2. data is not an array (i would say that's it)

    a) console.log(data), how does it look, is it an array?

    b) it's probably not an array and there is something like a nested "data" array inside, so use that

Did you try converting it using JSON.parse() from string, maybe server is returning the response in string form. Also the condition you added data && images.map.... , here data will be true always

Can you show what you got after logging (data[0])?

If you want to make sure your console.log statement doesn't have an error when accessing data[0].type then you can put the statement inside a useEffect like the following:

useEffect(() => {
  if (data) {
    console.log(data[0].type);
  }
}, [data]);

Hopefully this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM