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):

And here is the condition after reloading my browser:

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