Home > Software design >  API Data not showing in React JS
API Data not showing in React JS

Time:11-01

Once i type in a number between 1 - 20 data in the entry box it should display my query. Unfortunately it's doesn't show me any data. I think i've configure the application correctly.

Any suggestions?

I've tried a few methods to no prevail.

import React, { useState } from 'react'
import axios from 'axios'

function App() {
  const [data, setData] = useState({})
  const [LocalAuthorityId, setLocation] = useState('')

  const url = `http://api.erg.ic.ac.uk/AirQuality/Daily/MonitoringIndex/Latest/LocalAuthorityId=${LocalAuthorityId}/Json`

  const searchLocation = (event) => {
    if (event.key === 'Enter') {
      axios.get(url).then((response) => {
        setData(response.data.DailyAirQualityIndex.LocalAuthority)
        console.log(response.data.DailyAirQualityIndex.LocalAuthority)
      })
      setLocation('')
    }
  }

  return (
    <div className="app">
      <div className="search">
        <input
          value={LocalAuthorityId}
          onChange={event => setLocation(event.target.value)}
          onKeyPress={searchLocation}
          placeholder='Enter Location'
          type="text" />
      </div>
      <div className="container">
        <div className="top">
          <div className="location">
            <p>{data.LocalAuthorityName}</p>
          </div>
          <div className="temp">
          {data.site ? <p>{data.site[0].SiteName}</p> : null}
          </div>
          <div className="description">
            {data.site ? <p>{data.site[1].SiteName}</p> : null}
          </div>
        </div>

        {data.name !== undefined &&
          <div className="bottom">
            <div className="feels">
              {data.main ? <p className='bold'>{data.Site[0].Species[0].AirQualityBand}</p> : null}
              <p>Feels Like</p>
            </div>
            <div className="humidity">
              {data.main ? <p className='bold'>{data.Site[1].Species[1].AirQualityBand}</p> : null}
              <p>Humidity</p>
            </div>
            <div className="wind">
              {data.wind ? <p className='bold'>{data.Site[1].Species[2].AirQualityBand}</p> : null}
              <p>Wind Speed</p>
            </div>
          </div>
        }



      </div>
    </div>
  );
}

export default App;

I would appreciate any feedback or comments on the code.

CodePudding user response:

The JSON you receive contains properties that start with @ symbol

Site: Array(2)
0: 
@BulletinDate: "2022-10-30 00:00:00"
@Latitude: "51.563752"
@LatitudeWGS84: "6721627.34498"
@Longitude: "0.177891"
@LongitudeWGS84: "19802.7355367"
@SiteCode: "BG1"
@SiteName: "Barking and Dagenham - Rush Green"
@SiteType: "Suburban"

Access them using the indexing accessor []

<div className="location">
   <p>{data['@LocalAuthorityName']}</p>
</div>
  • Related