[Vuejs]-How to save axios request in vue.js store correclty?

0๐Ÿ‘

  1. Create a copy of routes of charts in store

    const state = {
      chartsRoutes: []
    }
    
  2. Create a computed property in component

    computed: {
      chartsRoutes () {
        return this.$store.state.chartsRoutes
      }
    }
    
  3. Use v-for to render chartsRoutes into router-links in component

  4. Create a mutation to modify store and router

    // import router
    const mutations = {
      'update-charts-routes': function (state, payload) {
        const { chartsRoutes } = payload
        state.chartsRoutes = chartsRoutes.map(r => {
          return {
            path: '/your/custom/path/according/to/response'
            // other params
          }
        })
        router.addRoutes(state.chartsRoutes)
      }
    }
    
  5. Create an action

    const actions = {
      'reload-charts': function ({commit, dispatch}, data) {
        return new Promise((resolve, reject) => {
          const r = {
            method: 'get',
            url: data.url,
            // add more options, e.g. header or auth
          }
          axios.request(r)
            .then(resp => {
              commit('update-charts-routes', { chartsRoutes: resp.data })
              resolve()
            })
            .catch(err => {
              // handle error
              reject(err)
            })
          }
        }
      }
    }
    
  6. Dispatch action

    this.$store.dispatch('reload-charts', { url: 'http://some.host/path/to/url' })
      .then(() => {
        // other stuff
      })
    

Leave a comment