I have a store.js file which sends an api request and gets responses using axios, the api is tested and working perfectly. store.js contains this code :
import V
Let me show you an example about how to use the Vuex store:
// main.js
import Vue from 'vue';
import App from './App.vue';
import store from '@/store/index';
new Vue({
el: '#app',
store,
components: {
App
},
render: h => h(App)
});
Now the store.js file:
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios'
Vue.use(Vuex);
const state = {
responseData: []
}
const mutations = {
setResponse(state, data) {
state.responseData = data;
}
}
const actions = {
async viewResults({ commit }, payload) {
let token =localStorage.getItem('token');
let username= payload.username;
await axios.post('search', { token, username }).then(response => {
commit('setResponse', response.data);
}).catch(er=>{
console.log(er);
});
}
}
export const store = new Vuex.Store({
state,
mutations,
actions
});
And a component to call the action and show the information:
// SearchAndShowData.vue component
<template>
<div>
<button click="search">
Search
</button>
{{ responseData}}
</div>
</template>
<script>
import {mapActions, mapState} from 'vuex';
export default {
name: "SearchAndShowData",
data: () => ({
username: "Andres",
}),
computed() {
// Expose the state.responseData object as responseData
...mapState(['responseData']) // If you want to preprocess the data, use create a getter and use mapGetters
// As a computed property, it will be updated always that responseData has any change
},
methods: {
...mapActions(["viewResults"]), // Expose the viewResults action as a method, call it with this.viewResults
search() {
this.viewResults({username: this.username })
}
}
}
</script>
I didn't test it, but this is the idea behind a vuex store and how to use it, if somebody sees an error, please let me know to update the answer (thanks).
Hope you can update your code with this information and it can work properly.
Also, Scrimba has a free course that could help you to extend your knowledge about Vuex, check it here