Returning value from a function in react

前端 未结 2 1185
失恋的感觉
失恋的感觉 2021-01-23 10:08

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

<

相关标签:
2条回答
  • 2021-01-23 10:44

    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();
    
    0 讨论(0)
  • 2021-01-23 10:51

    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));
    }
    
    0 讨论(0)
提交回复
热议问题