1

When I'm trying to return my res.data from my function and then console.log it I get undefined but if I console.log it from inside the function I get the normal result

const getDefaultState = () => {
  axios
    .get("http://localhost:5000/urls/todos")
    .then((res) => {
      if (res.data) {
        console.log(res.data);
        return res.data;
      }
    })
    .catch((err) => console.log(err));
};


console.log(getDefaultState());

so I get first

(3) [{…}, {…}, {…}]

(the normal value) but then from outside I get

undefined

3
  • 2
    You can use async/await Commented Sep 17, 2020 at 12:39
  • As @SirwanAfifi suggests it, you get undefined because when you console.log(getDefaultState()), your request is still processing. See this Commented Sep 17, 2020 at 12:42
  • 1
    Please be aware that getDefaultState will never return the "real" value. The best you can do is have it return a promise. Commented Sep 17, 2020 at 12:48

2 Answers 2

1

You need to return the call as well:

const getDefaultState = () => {
  return axios.get("http://localhost:5000/urls/todos")
        .then((res) => {
           if (res.data) {
              console.log(res.data);
              return res.data;
           }
  }).catch((err) => console.log(err));
}
Sign up to request clarification or add additional context in comments.

Comments

0

You should return the promise instead.

const getDefaultState = () =>
  axios
    .get("http://localhost:5000/urls/todos")
    .then((res) => {
      if (res.data) {
        console.log(res.data);
        return res.data;
      }
    })
    .catch((err) => console.log(err));

That way you can listen to the result outside the function:

getDefaultState().then(/* do stuff */);
// or
const res = await getDefaultState();

3 Comments

Bear in mind that since there are cases where you don't return anything inside the 'then' clause and you never return anything in the 'catch' clause, you could still get undefined/null. But as long as the promise resolves correctly and there is data, you will recieve it this way.
Don't forget async if you want to use await
You mind want to point out what it is you changed (removed the brackets).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.