Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get data from API in vuex using axios?

Tags:

vue.js

vuex

I have data taken from API laravel, and here is my code in state.js

import axios from 'axios'
import {apiPostGet} from '../api/api'
export default {
  data: axios({
    method: 'GET',
    url: apiPostGet('Kategori')
  }).then(
    response => {
      return response.data.kategori
    }
  ).catch(
    error => {
      return error.response
    }
  )
}

and this is my code in gteeters.js

export default {
  datas: state => {
    return state.data
  }
}

and this is my code in index.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'

Vue.use(Vuex)

export default new Vuex.Store({
   state,
   getters
})

and this picture from dev tool vue js

like image 463
tejoprabowo Avatar asked Jan 26 '18 02:01

tejoprabowo


People also ask

How do I get data from Vue API?

Vue Fetch data from API example To get the actual JSON body of the response, we use response. json() method. We can also access metadata such as headers , status , statusText , type , url from the Response object. The response Promise does not reject on HTTP errors (for example: 404 , 500 ).

What is the difference between Axios and Vue-Axios?

vue-axios is just a wrapper, exposing axios to components as this. axios , this. $http , or Vue. axios .

What is Vuejs Axios?

Axios is a popular JavaScript library used to make HTTP requests. It is a promise-based HTTP client used in JavaScript or with other Javascript libraries like Vue. js or React. js. Due to its isomorphic nature, Axios can run on the client and server-side simultaneously using the same codebase.


1 Answers

Data hook needs to return synchronously. You have to add the loading to created or mounted and just add the properties to data / state, so reactivity is working.

The loading of the data with Axios needs to be triggerd with an action because it's asynch. Mutations need to run synchronous. I've added the initial loading in created. (mounted would also work.)

I've used the Vuex helper mapState to map the state properties to the component. Using getters would also work but mapState is easier to write.

Please have a look at the demo below or this fiddle.

Also uncomment the code below the Vuex version in the fiddle and comment the app above to see how Axios is working with-out Vuex for a better understanding.

const URL = 'https://jsonplaceholder.typicode.com/posts';

const store = new Vuex.Store({
  state: {
    posts: [],
    loading: true
  },
  actions: {
    loadData({
      commit
    }) {
      axios.get(URL).then((response) => {
        // console.log(response.data, this)
        commit('updatePosts', response.data)
        commit('changeLoadingState', false)
      })
    }
  },
  mutations: {
    updatePosts(state, posts) {
      state.posts = posts
    },
    changeLoadingState(state, loading) {
      state.loading = loading
    }
  }
})

new Vue({
  el: '#app',
  computed: Vuex.mapState(['posts', 'loading']),
  store,
  created() {
    //console.log(this.$store)
    this.$store.dispatch('loadData') // dispatch loading
  }
})

/*
	//example with-out vuex
  
new Vue({
	el: '#app',
	data() {
  	return {
    	loading: true,
      posts: [] // add posts here so reactivity is working, also undefined would be OK
    }
  },
  created() {
  	//this.loading = true --> not needed already set in data
  	axios.get(URL).then((response) => {
    	// console.log(response.data, this)
      this.posts = response.data
      this.loading = false
    })
  }
})

*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
<div id="app">
  <div v-if="loading">
    loading...
  </div>
  <div v-else>
    <ul>
      <li v-for="post in posts">
        <h1>
          {{post.title}}
        </h1>
        <p>
          {{post.body}}
        </p>
      </li>
    </ul>
  </div>
</div>
like image 90
AWolf Avatar answered Oct 20 '22 17:10

AWolf