LoginSignup
0

More than 1 year has passed since last update.

HTTPでgetしたデータがconsole.logで見えないと思ったら非同期処理が原因だったらしい

Last updated at Posted at 2022-03-21

HTTPでgetしたデータがない

vueで以下のようなコードを書いていたが、console.logにはなにも出力されなかった。
HTTPでgetしたデータをthis.postに代入して出力させているつもりだったが、確認できない。

  mounted() {
    const url = location.pathname;
    const id = url.replace(/[^0-9]/g, "");
    axios
      .get(`/api/v1/posts/${id}.json`)
      .then((response) => (this.post = response.data));
    console.log(`this.post: ${JSON.stringify(this.post)}`);
  }

ただ、その後の処理は問題なく動作しているので、HTTPのgetは成功している様子。

原因と修正内容

メンターの方に伺ったところ、非同期処理が原因とのことだった。
以下のように修正したらconsole.logでみえるようになった。

  mounted() {
    const url = location.pathname;
    const id = url.replace(/[^0-9]/g, "");
    console.log(`this.post_1: ${JSON.stringify(this.post)}`);
    axios
      .get(`/api/v1/posts/${id}.json`)
      .then(
        (response) => (
          (this.post = response.data),
          console.log(`this.post_2: ${JSON.stringify(this.post)}`)
        )
      );
  },

各コード毎の非同期処理動作イメージ

以下のサイトを参考に今回のコードの動作イメージを作成してみた
参考サイト
参考qiita
参考youtube

最初のコードの動作イメージ

問題イメージ.gif

このコードでは、

コードA
.then((response) => (this.post = response.data));
コードB
console.log(`this.post_2: ${JSON.stringify(this.post)}`);

上記2つのコードがそれぞれセミコロンで分割されてしまっているから、コードAがコードBの後に処理されてしまったために、console.logでは、何も表示されなかった。

コード修正後の動作イメージ

修正イメージrev03.gif

修正後のコードでは、

.then(
   (response) => (
          (this.post = response.data),
          console.log(`this.post_2:${JSON.stringify(this.post)}`)
   )
)

上記のように2つのコードを一つにまとめることで、一緒に非同期処理されるからconsole.logにちゃんとHTTPでgetしたデータが出力された。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0