Fetching data from a third party api with vuex and axios is going to be todays tutorial. Hello devs in this tutorial i will show you how we can fecth api data by using vuex. You know that vuex is a great state management library for vue js application.
Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.
In this example i will simply fetch users from a third party api. In this vuex example my concern is to teach you that how you can use and setup vuex in your vue js application. Also in this vuex state management example i will use axios to fecth api data.
Using vuex we can easily manage our state. Because If your components need to share and update state then you need it. So what is state management pattern?
Let's start with a simple Vue counter app:
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `
< div >{{ count }}< /div >
`,
// actions
methods: {
increment () {
this.count++
}
}
})
It is a self-contained app with the following parts:
This is a simple representation of the concept of "one-way data flow":
However, this simplicity quickly breaks down when we have multiple components that share a common state:
For problem one, to pass props can be tedious for deeply nested components, and simply doesn't work for sibling components.
For problem two, we often find ourselves resorting to solutions such as to reach for direct parent/child instance references or trying to mutate and synchronize multiple copies of the state via events. Both of these patterns are brittle and quickly lead to unmaintainable code.
So for solving this all the issues together we can use vuex. It's a n amazing library to handle your state. It doesn't matter how many component or siblings component your are going to use and going to manage your state. it is always ready to reduce your hard work for managing your state.
Vuex backend api
SO let's start our vuex tutorial. Now, create a Vue project by running the following code in your terminal:
vue create vuex-app
Now we have to install vuex and axios. So open terminal and run both command one after another
npm install vuex
//then
npm install axios
In your store
folder, create a file and name it index.js like below code
├── index.html
└── src
├── components
├── App.vue
└──store
└── index.js # where we assemble modules and export the store
Next, in your store/index.js
file, input the following code:
vuex-app/src/store/index.js
import axios from 'axios'
import Vuex from 'vuex'
import Vue from 'vue'
//load Vuex
Vue.use(Vuex);
//to handle state
const state = {
posts: []
}
//to handle state
const getters = {
}
//to handle actions
const actions = {
getPosts({ commit }) {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
commit('SET_POSTS', response.data)
})
}
}
//to handle mutations
const mutations = {
SET_POSTS(state, posts) {
state.posts = posts
}
}
//export store module
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
Now we have to register our store in our your main.js
file:
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App),
}).$mount('#app')
Now open your main App.vue file and paste this below code
vuex-app/src/App.vue
Remember that mutation handler functions must be synchronous, and that you can commit mutations in components with this.$store.commit('xxx')
, or use the mapMutations
helper, which maps component methods to store.commit
.
Now if you run your application you will see the following output
Also you can check your vue devtools, you will be able to see the below output
Look here above we fetch data without using getters. But you can use it. But remember, With Vuex, getters do not actually store a value. Instead, they retrieve and set Vuex state indirectly.
Remember that Vuex getters receive the state as their first argument and can receive other getters as the second argument. MapGetters
is a helper that maps store getters to local computed properties.
So update your getters like that
//to handle state
const getters = {
allPosts: (state) => {
return state.posts
}
}
And update it also in your App.vue like that
computed: {
posts() {
return this.$store.getters.allPosts;
}
},
You will see the same output. Hope you got the point to understand it. You can also use mapGetters helper like that
import { mapGetters } from 'vuex';
export default {
name: 'App',
data () {
return {
msg: 'We are learning vuex!!'
}
},
computed: mapGetters(['allPosts']),
mounted() {
this.$store.dispatch("getPosts");
}
}
And pass allPosts in your for loop like that
Recommended : React Redux Complete Setup Example with Api Call
You will see the same output. Hope this vue js vuex tutorial you will help you to learn something new.
#vue-js #vuex #api #axios