I'm using axios and useEffect to do my get request but it doesn't work when my page is loaded

Viewed 23

When i refresh the page, my object is empty but when i go back in the code, change something and save it, the request is made again, with no refresh, successfuly and contain the expected result.

 const [specialities, setSpecialities] = useState([])
 const getData = async ()=> {

   await axios.get(getURL).then((response)=>{
     setSpecialities(response.data)
     console.log(specialities, "specialeties are displayed here")
   })
 } 

 useEffect(()=>{
   getData()
 }, [])```

Here i remove the accolades in my useEffect and it works, my response is full when i reload but the request is made infinitely.

const [specialities, setSpecialities] = useState([])
const getData = async ()=> {

await axios.get(getURL).then((response)=>{
  setSpecialities(response.data)
  console.log(specialities, "specialesss")
})}

useEffect(()=>{
 getData()
})
1 Answers

For class component,

  this.setState(response.data)
     console.log(specialities, "specialeties are displayed here")

You cannot get the specialities data just after setting it. It takes some time to set the data.

The below code would work as we have a callback after setting the state.

  this.setState(response.data, function() {
    console.log(specialities, "specialeties are displayed here")   });

For functional component,

 useEffect(() => { console.log(specialities); },[specialities); 
Related