0

I'm Having some trouble with this function on a React project

let fetchData = async (event, imagen) => {
    const apiURL = `https://some_api_call/${imagen}`;
    await axios.get(apiURL).then((response) => {
      console.log(response.data.Imagen1.data);
      return response.data.Imagen1.data;
    });

When i call it the Console.log returns Undefined but the console log above returns the data

fetchData(event, rowData.Codigo).then(function (response) {
console.log(response);
});
5
  • 5
    You need to return the awaited axios call in the function. Commented Dec 22, 2020 at 19:45
  • Thank you for the comment, do you mean like " return await axios.get..."? Commented Dec 22, 2020 at 19:46
  • Yes, that's correct. Commented Dec 22, 2020 at 19:48
  • 1
    that indeed would return the promise and then you can use the .then or you can even let response=await fetchData(...args) Commented Dec 22, 2020 at 19:49
  • Thank you both for the answer it worked like a charm. Commented Dec 22, 2020 at 19:53

2 Answers 2

1
let fetchData = async (event, imagen) => {
    const apiURL = `https://some_api_call/${imagen}`;
    return await axios.get(apiURL);
}
fetchData(event, rowData.Codigo).then(function (response) {
    console.log(response);
});
Sign up to request clarification or add additional context in comments.

1 Comment

ok i had a small syntax error.. it's fixed now
1

Your fetchData function has no return statement. You probably don't want to use then when there is await:

async function fetchData(event, imagen) {
  const apiURL = `https://some_api_call/${imagen}`;
  const response = await axios.get(apiURL)
  console.log(response.data.Imagen1.data);
  return response.data.Imagen1.data;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.