Home > Software engineering >  Need help on getting data from API with axios
Need help on getting data from API with axios

Time:11-03

I recently learn about getting data from REST API using axios, but I encounter a problem. So I want to fetch some data from an API, here is my code:

import {useState, useEffect} from 'react'
import axios from 'axios'
import { Popup, GeoJSON } from 'react-leaflet'
import '../Map.css'

const GradientMap = () => {
 const [data, setData] = useState([]);

 useEffect(()=>{
    getData();
 })
 const getData = async ()=>{
    const response = await axios.get('http://localhost:5000/in-data')
    setData(response.data)
 }

 const getColor = (name)=>{...
 }

 return (
    <div>
        <GeoJSON data={CIKARANG_UTARA} style={{color: getColor(CIKARANG_UTARA.features[0].properties.Name)}}>
            <Popup>
                {CIKARANG_UTARA.features[0].properties.Name} <br/> Total Weight: {data[0].Total_Weight}
            </Popup>
        </GeoJSON>
        <GeoJSON data={CIKARANG_BARAT} style={{color: getColor(CIKARANG_BARAT.features[0].properties.Name)}}>
            <Popup>
                {CIKARANG_BARAT.features[0].properties.Name} <br/> Total Weight: {data[1].Total_Weight}
            </Popup>
        </GeoJSON>
        <GeoJSON data={CIKARANG_TIMUR} style={{color: getColor(CIKARANG_TIMUR.features[0].properties.Name)}}>
            <Popup>
                {CIKARANG_TIMUR.features[0].properties.Name} <br/> Total Weight: {data[2].Total_Weight}
            </Popup>
        </GeoJSON>
        <GeoJSON data={SUKATANI} style={{color: getColor(SUKATANI.features[0].properties.Name)}}>
            <Popup>
                {SUKATANI.features[0].properties.Name} <br/> Total Weight: {data[3].Total_Weight}
            </Popup>
        </GeoJSON>
        <GeoJSON data={CIBITUNG} style={{color: getColor(CIBITUNG.features[0].properties.Name)}}>
            <Popup>
                {CIBITUNG.features[0].properties.Name} <br/> Total Weight: {data[4].Total_Weight}
            </Popup>
        </GeoJSON>
    </div>
 )
}

export default GradientMap

The error is in the data[0].Total_Weight, it works when I save the file, but after I reload my browser it becomes an error, I tried to do console.log(data) and it returns an empty array. The API works fine, here is the response:

[
 {
  "Area": "CIKARANG UTARA",
  "Total_Weight": 283,
  "Total_OR_Weight": 135,
  "Total_IN_Weight": 148
 },
 {
  "Area": "CIKARANG BARAT",
  "Total_Weight": 0,
  "Total_OR_Weight": 0,
  "Total_IN_Weight": 0
 },
]

Here is the condition before reloading the browser (you can see, there is no error and the total weight fetched successfully): before

And here is the condition after reloading my browser: after

I don't know what to do, I am new to react and axios, thanks in advance

CodePudding user response:

You're creating an empty array:

const [data, setData] = useState([]);

Then trying to read the first value from that empty array:

Total Weight: {data[0].Total_Weight}

Since the array is empty, the first element of that array is undefined.

What you can do is conditionally not render the elements until the array has values. For example:

return (
  data.length > 0 ?
  <div>
    ... the rest of your HTML
  </div> :
  <div>Loading...</div>
);

You can replace that "loading" element with whatever you want to show on the page while the API data is being fetched. But you can't use the API result until after it's fetched, at which point updating the state will trigger the component to re-render with the data.

  • Related