reactの関数からの戻り値

Sep 17 2020

関数からres.dataを返してからconsole.logを返そうとすると、未定義になりますが、関数内からconsole.logを返すと、通常の結果が得られます。

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

だから私は最初に

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

(通常値)でも外からは

未定義

回答

1 Jai Sep 17 2020 at 12:45

また、コールを返す必要があります。

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));
}
eloyra Sep 17 2020 at 12:42

代わりに約束を返す必要があります。

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

そうすれば、関数の外で結果を聞くことができます。

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