I'm trying to use axios for API requests. My code looks like this.
const trigger = async () => {
for (const [key, value] of Object.entries(data)) {
if (value.name == source){
return await axios.get("http://localhost:8000/api/"+value.someid).then(
(response) => response.data
);
}
}
}
console.log(trigger())
Here, I'm trying to hit an endpoint for some id. And I got the promise result in console.log.
I thought I should get the response.data not the entire promise. Why is this?
Still getting the entire Promise with this code :(
const trigger = async () => {
for (const [key, value] of Object.entries(data)) {
if (value.name == source){
const response = await axios.get("http://localhost:8000/api/"+value.someid);
return response.data;
}
}
}
console.log(trigger())
In your question you are logging out trigger function without using await keyword, So the expected output for console.log(trigger()) would be a promise.
SOLUTION
You will need to await the trigger function call, but in order to use the await call you will need to it be inside an async function, since top level await is not yet supported.you will have to wrap the call inside an async function and use await to resolve the promise.
check the below code, I have used an Starwars API for simulating the question.
const trigger = async () => {
let response;
for (const [key, value] of Object.entries([1, 2, 3, 4, 5])) {
if (value === 2) {
console.log('passed');
response = await axios.get(`https://swapi.dev/api/people/${value}`);
}
}
return response;
};
const getData = async () => {
const response = await trigger();
console.log(response);
};
here is the sample react code in stack blitz
You need to await trigger() or use .then to wait for the Promise to resolve. Also, I would recommend using either async/await or Promise.then() and not combining them:
const response = await axios.get("http://localhost:8000/api/"+value.someid);
return response.data;
or
return axios.get("http://localhost:8000/api/"+value.someid).then(
(response) => response.data
);