LoginSignup
10
9

More than 5 years have passed since last update.

Vuexでasync/awaitを使いたい時の書き方

Last updated at Posted at 2017-03-09

Vuexのactionでasync/awaitを使いたい時の書き方です。

■■■修正前■■■

sample.js
import axios from 'axios'

export default {
  [FETCH_DATA] ({ commit }) {
    axios.get('/api/data1').then((response1) => {
      axios.get(`/api/data2?${response1.id}`).then((response2) => {
        commit(FETCH_DATA, response2.data)
      }).catch((error) => {
        console.log(error)
      })
    }).catch((error) => {
      console.log(error)
    })
  }
}

■■■修正後■■■

sample.js
import axios from 'axios'

export default {
  [FETCH_DATA]: async ({ commit }) => {
    const response1 = await axios.get('/api/data1').catch((error) => {
      console.log(error)
    })
    const response2 = await axios.get(`/api/data2?${response1.id}`).catch((error) => {
      console.log(error)
    })
    commit(FETCH_DATA, response2.data)
  }
}

■■■1/12追記■■■
こっちの方が綺麗な書き方かも

async [FETCH_DATA]({ commit }) {
・・・
}
10
9
0

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
  3. You can use dark theme
What you can do with signing up
10
9