ethantest
ethantest

Reputation: 11

Returning value from a function in react

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

Upvotes: 1

Views: 2672

Answers (2)

Jai
Jai

Reputation: 74738

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));
}

Upvotes: 1

eloyra
eloyra

Reputation: 529

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();

Upvotes: 0

Related Questions