I've seen similar questions to this, but none of them answer my question. For the code, it's this.
const [raceData, updateRaceData] = useState();
const [raceChosen, updateRaceChosen] = useState();
const url = "http://localhost:5000/races/viewraces";
useEffect(() => {
Axios.get(url)
.then((response) => {
const allRaces = response.data.races;
updateRaceData(allRaces);
})
.catch((error) => console.error(`Error: ${error}`));
}, []);
console.log(raceData[0]);
So when I console.log() raceData and raceData[0] or raceData1, it works and doesn't give me any trouble. But if I instead do console.log(raceData[0].race), and then refresh, it starts telling me :
TypeError: Cannot read properties of undefined (reading 'race')
Any help on figuring out why trying to access things from the response I'm getting doesn't fully work would be appreciated.
Edit: Here is the object response with raceData[1]: Response object
CodePudding user response:
The browser is running console.log(raceData[0]) before the variable being assigned. Try raceData && console.log(raceData[0]);
which will only execute the console.log()
if raceData is assigned.
CodePudding user response:
Try mapping over the racedata as such:
raceData?.map((race) => console.log(race))
this should populate your raceData info