I built a react code using useEffect()
and Axios to get a json from an URL, however I'm getting an empty array, probably because it is not async function. Here is my code:
import axios from "axios";
import { useEffect, useState } from "react";
export function UseVacation (){
const[vacations, setVacations] = useState([]);
useEffect(() =>{
axios.get('APILINK').then( async (res) =>{
setVacations(res.data);
console.log("vactest: " JSON.stringify(vacations))
}).catch((err)=>{
alert("Error extracting the data from API: " err);
})
}, [])
return (
<div>
{vacations.map( (vac) => {
<h1>{vac._id}</h1>
})}
</div>
)
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Any idea on this?
CodePudding user response:
Why dont you console res.data instead of vacations and see what it has ? Also check the network tab, and see what actual request has in the response
CodePudding user response:
Have you tried the following?
return (
<div>
{vacations && vacations.map( (vac) => {
<h1>{vac._id}</h1>
})}
</div>
)
CodePudding user response:
I have good suggestion for you:
const[vacations, setVacations] = useState([]);
useEffect(() => {
const getApi = async () => {
try {
const res = axios.get('APILINK')
setVacations(res.data);
} catch(error) {
console.log(error)
}
}
getApi()
}, [])
console.log("vactest: " vacations)
I cannot explain but if you set state in useEffect and direct log state in useEffect, it only log previous state