Home > Software engineering >  api fetches data but i can't see in varible nor in state
api fetches data but i can't see in varible nor in state

Time:12-12

I have a function which fetches data from api like this

export const getAudio = (id) =>{
axios.get(`url${id}`)
.then((data)=>{
  console.log(data.data) //I can see this log in console
  return (data.data);
  })
};

I imported this fn in a component and add a onclick eventlistener fn

const getAudioHandler =(e)=>{
    console.log(e.target.id) //I can see this too
    let du = getAudio(e.target.id)
    du && console.log(du) //But not this
    du && setCurrentSong(du) //Neither this
  }

which means that the api runs correctly and send data, which i can see from the console.log inside the getaudio() but inside getAudioHandler() i can neither see the data nor my state changes.

What am i doing wrong here?

Another issue is even if I put async/await like this

const getAudioHandler = async (e)=>{
    console.log(e.target.id) //I can see this too
    let du = await getAudio(e.target.id)
    du && console.log(du) //But not this
    du && setCurrentSong(du) //Neither this
  }

this popup appears in vs code and it doesn't help, the problem remains same

CodePudding user response:

Do these changes, you will be able to see data.

export const getAudio = (id) =>{
  return axios.get(`url${id}`);
};

    
const getAudioHandler = (e)=>{
  console.log(e.target.id);
  getAudio(e.target.id).then(data => {
     data && console.log(data.data);
     data && setCurrentSong(data.data);
 })
}
  • Related