Home > Mobile >  multiple axios inside useEffect
multiple axios inside useEffect

Time:11-05

i need to do something like this.

  const [token, setToken] = useState('')

const urlAuth = 'http://localhost:8624/login'
const bodyData = {
  username: 'training',
  password: 'traiOA9876'
}
const data = {
  headers: {
    'Content-Type': 'application/json'
  }
}

console.log(token)

const dataListUrl = 'http://localhost:8624/locations'
const headers2 = {
  headers :{
    'Authorization': `Token ${token}`,
    'Content-Type': 'application/json'
  }
}

useEffect(() => {  
  //console.log(token)
  async function getPost() {
    const response = await axios.post(urlAuth, bodyData, data )  
      console.log(response.data.token)
      setToken(response.data.token); 

  } 
  async function GetData(){

    const response2 = await axios.get(dataListUrl, headers2)
    console.log (response2)
  }

    getPost();
    GetData();
  
}, [setToken])

I need to do a first axios call, to get the Token from the server. (this part works!!!) But then i need to use this token in the second axios call, to get the data from the API. In my postman works, but here i can not resolve the second part.

I tryed this too, but didn't work:

const [token, setToken] = useState('')

const urlAuth = 'http://localhost:8624/login'
const bodyData = {
  username: 'training',
  password: 'traiOA9876'
}
const data = {
  headers: {
    'Content-Type': 'application/json'
  }
}



console.log(token)

const dataListUrl = 'http://localhost:8624/locations'
const headers2 = {
  headers :{
    'Authorization': `Token ${token}`,
    'Content-Type': 'application/json'
  }
}

useEffect(() => {  
  //console.log(token)
  axios.post(urlAuth, bodyData, data )    
      .then((response) => {
        //console.log(response)
        let tokenRes = response.data.token;
        setToken(tokenRes)
          console.log(tokenRes)  
          axios.get(dataListUrl, headers2)
          .then((res) => {
            console.log(res)}) 
        
        } 
      )
   
  
}, [setToken])

Thanks for your time and your help!!

CodePudding user response:

React's setState is asynchronous, that means you can't expect the token to be there once you call setToken(). In order to solve this, you need to wrap your second api call inside a useEffect hook passing the token as a dependency.

useEffect(() => {
 // your getData api call goes here
}, [token])

CodePudding user response:

useEffect(() => {  
//console.log(token)
axios.post(urlAuth, bodyData, data )    
  .then((response) => {
    //console.log(response)
    let tokenRes = response.data.token;
    setToken(tokenRes)
      console.log(tokenRes)
      //you need a return statement if you want to chain an another 'then' otherwise it will be returning undefined 
      return axios.get(dataListUrl, headers2)
      .then((res) => {
        console.log(res)}) 
    
    } 
  )
}, [setToken])

Or you can do what kamal said

  • Related