0

So I have a fetch request that returns this json:

{
   "data":[
      {
         "latitude":44.43225,
         "longitude":26.10626,
         "type":"locality",
         "name":"Bucharest",
         "number":null,
         "postal_code":null,
         "street":null,
         "confidence":1,
         "region":"Bucharest",
         "region_code":"BI",
         "county":null,
         "locality":"Bucharest",
         "administrative_area":null,
         "neighbourhood":null,
         "country":"Romania",
         "country_code":"ROU",
         "continent":"Europe",
         "label":"Bucharest, Romania"
      }
   ]
}

In the component I want to show the latitude and longitude and I tried this way:

const conditions = (props) => {
    return (
        <div className={classes.Wrapper}>
            {
                props.error && <small className={classes.Small} > Please enter a valid city. </small>}
            {
                props.loading && < div className={classes.Loader} />}

            {
                props.responseObj.cod === 200 ?
                    <div className={classes.information}>
                        <p>{props.geoObj.data[0].longitude}</p>
                        <p>{props.geoObj.data[0].latitude}</p>
                    </div > : null
            } </div>
    )
}

but it doesn't work. Can you please tell me what's wrong and how should I use the objects from the JSON response.

3 Answers3

0

I think that you have to convert JSON file to Obj first. Try JSON.parse()

This post may help: How to read an external JSON

Mike
  • 56
  • 1
  • 9
0

You used it properly. But when you fetching data, props geoObj hasn't structure like the fetch response.

You need to use [optional chaining][1] to avoid issues related:

{props.geoObj?.data?.[0]?.longitude}
Viet
  • 12,133
  • 2
  • 15
  • 21
0

like this?

const props = {
  "data":[
     {
        "latitude":44.43225,
        "longitude":26.10626,
        "type":"locality",
        "name":"Bucharest",
        "number":null,
        "postal_code":null,
        "street":null,
        "confidence":1,
        "region":"Bucharest",
        "region_code":"BI",
        "county":null,
        "locality":"Bucharest",
        "administrative_area":null,
        "neighbourhood":null,
        "country":"Romania",
        "country_code":"ROU",
        "continent":"Europe",
        "label":"Bucharest, Romania"
     }
  ]
}

type Data = typeof props.data[0]
const Condition = (props: Data) => <div>{
  JSON.stringify(props)}</div>

const Parent = () => {
  return <div>
    {
      props.data.map(data => <Condition {...data} />)
    }
  </div>
}