i'm using axios package for get data. my codes are not working in function. can you say me my problem ?
This code is working
axios.get('testurl').then(res => {
data = res.data
}).catch(err=>{
if(err)
data = 0
})
console.log(data)
But if i use function
const Tsingle = url => {
let data = null;
axios.get(url).then(res => {
data = res.data
}).catch(err=>{
if(err)
data = 0
})
return data
}
console.log(Tsingle('testurl'))
Can i example 2 with function in ? Thank you.
CodePudding user response:
it should be an async function
const Tsingle = async (url) => {
try {
const response = await axios.get(url);
console.log(response);
return response.json()
}
catch (error) {
console.log(error);
}
}