[Vuejs]-How to set state from an external API in Vuex store

0👍

I’ve made this example on how to set the state from external service using axios

// main.js

import Vue from "vue";
import App from "./App.vue";
import Vuex from "vuex";
import axios from "axios";

Vue.config.productionTip = false;

Vue.use(Vuex);

const store = new Vuex.Store({
  // create the state to store the data
  state: {
    todo: {}
  },

  // make an asynchronous call to get the data
  actions: {
    getTodoItem(state, index) {
      return axios.get(`https://jsonplaceholder.typicode.com/todos/${index}`);
    }
  },

  // set data in state
  mutations: {
    setTodo(state, value) {
      Vue.set(state, "todo", value);
    }
  }
});

new Vue({
  store, // loads the store
  render: h => h(App)
}).$mount("#app");
<!-- App.vue -->

<script>
import { mapState, mapActions, mapMutations } from "vuex";

export default {
  computed: {
    ...mapState(["todo"]),
    hasTodo() {
      return Object.keys(this.todo).length;
    }
  },
  methods: {
    ...mapActions(["getTodoItem"]),
    ...mapMutations(["setTodo"]),

    async getTodo() {
      // random number between 1 and 200
      const index = Math.floor(Math.random() * 200) + 1;
      const { data } = await this.getTodoItem(index);
      this.setTodo(data);
    }
  },
  mounted() {
    this.getTodo();
  }
};
</script>


<template>
  <div id="app">
    <div v-if="hasTodo">Todo: {{ todo.title }}</div>
    <b v-else>Loading..</b>
  </div>
</template>

https://codesandbox.io/s/vue-template-y69be

Leave a comment