How to fetch data from api in vuex?

by dalton_moen , in category: Javascript , 2 months ago

How to fetch data from api in vuex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 2 months ago

@dalton_moen 

To fetch data from an API in Vuex, you can create an action in your Vuex store that makes a request to the API using a library like axios. Here's an example of how you can fetch data from an API in Vuex:

  1. First, install axios in your project by running the following command:
1
npm install axios


  1. In your Vuex store file (typically store/index.js), import axios and define an action that makes a request to the API:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import axios from 'axios';

// Define your Vuex store
const store = {
  state: {
    data: [],
    error: null
  },
  mutations: {
    setData(state, data) {
      state.data = data;
    },
    setError(state, error) {
      state.error = error;
    }
  },
  actions: {
    fetchData({ commit }) {
      axios.get('https://api.example.com/data')
        .then(response => {
          commit('setData', response.data);
        })
        .catch(error => {
          commit('setError', error);
        });
    }
  }
};

export default store;


  1. In your component, you can dispatch the fetchData action to fetch data from the API:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<template>
  <!-- Your component template -->
</template>

<script>
export default {
  name: 'MyComponent',
  mounted() {
    this.$store.dispatch('fetchData');
  }
};
</script>


By following these steps, you can fetch data from an API in your Vuex store and use it in your Vue components.