I have a useEffect hook in a react app that is used to call an async function making an axios request to our express server pulling JSON data. I am running into an issue where the data that is pulled from the request is not being set to a state variable correctly. In the code below, we console.log the data that is pulled from the request and it is outputting a single array of data, which was what we want. However, after setting the state variable with what was pulled, and logging the output of the state variable, it seems to be outputting more than the array. It is as if the state variable turned into an array of arrays, instead of just setting it to the same array as then data pulled. Is there a specific way we should be setting the state variable? In a previous useEffect function we make another api call to an outside source in a similar fashion and it seemed to set the state variable correctly. A screenshot of the terminal of our app showing the output of our state variable will be added below as well.
import { MapContainer, TileLayer, Marker, Popup, Circle } from "react-leaflet";
import React, { useState, useEffect } from "react";
import mockData from "./testData/MOCK_DATA.json";
import axios from "axios";
import outageData from "./testData/outageData.json";
function OutageIndicator({ outage }) {
//this component renders the markers with corresponding lat and long values calculated by the geocodify api.
const [coords, setCoords] = useState();
useEffect(() => {
async function resolveLocation() {
const resp = await axios.get(
"https://api.geocodify.com/v2/geocode/json?api_key=mykey&q=" +
outage.outage_street +
", " +
outage.outage_city +
", Michigan, USA"
);
const [lng, lat] = resp.data.response.bbox;
setCoords({ lng, lat });
}
resolveLocation();
}, [outage]);
return !coords ? (
"Loading"
) : (
<Marker position={[coords.lat, coords.lng]}>
<Popup>
{outage.service_type} {outage.service_name}
</Popup>
</Marker>
);
}
function OutageMap() {
//This is where the map page will be rendered.
const [allOutages, setAllOutages] = useState();
useEffect(() => {
async function fetchOutages() {
const resp = await axios.get("/outages");
const pulledOutages = resp.data.outages;
//console.log(pulledOutages); //This outputs a single array that is pulled from the api call
setAllOutages({ pulledOutages });
console.log(allOutages); //this outputs an array of arrays that are similar to pulledOutages
}
fetchOutages();
});
return (
<MapContainer center={[38.89, -77.059]} zoom={13} scrollWheelZoom={true}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
//outageData below is dummy data that was hard coded. This would change to allOutages once the state variable is set correctly.
{outageData.outages.map((mock) => (
<OutageIndicator outage={mock} />
))}
</MapContainer>
);
}
export default OutageMap;
