import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import api from "./api_key";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
data: "",
location: "New York"
},
mutations: {
GET_DATA(state, data) {
state.data = data;
}
},
actions: {
getData({ commit }, state) {
axios
.get(
`https://api.openweathermap.org/data/2.5/forecast/daily?q=${
state.location
}&appid=${api}&units=metric&cnt=5`
)
.then(data => {
commit("GET_DATA", data);
})
.catch(function(error) {
console.log(error);
});
}
},
getters: {
data(state) {
return state.data;
}
}
});
I am working on Vue web application. For state management I decided to use vuex. My "location" and "api" variables are undefined in my Axios request address.
to access your current state in your action, you misplaced the state
declaration in getData
. It should be like this: getData({ commit, state })
.
But yet, I don't understand why api
is undefined. Besides that, be carefull on the data
recuperation, it's more like this:
.then((response) => {
if (response.data) {
commit("GET_DATA", response.data);
}
}
EDIT:
Your api_key.js
file should contains something like this in order to work with the import you are using:
export default "my_api_key";