L
L
Luke LikeSkywalker2018-08-19 10:43:21
Vue.js
Luke LikeSkywalker, 2018-08-19 10:43:21

Vue js doesn't see nested objects of loaded data. What is the problem?

I am working on a weather app learning Vue and Vuex. I requested data via axios and saved it in state.data.

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, response) {
      state.data = response.data;
    }
  },
  actions: {
    getData({ commit, state }) {
      console.log(api);
      axios
        .get(
          `https://api.openweathermap.org/data/2.5/forecast/daily?q=${
            state.location
          }&appid=${api}&units=metric&cnt=5`
        )
        .then(response => {
          if (response.data) {
            commit("GET_DATA", response.data);
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  },
  getters: {
    city(state) {
      return state.data.city.name;
    }
  }
});

An error such
5b791e7f35aa5897066771.png
If to send through a getter simply state.data.city problems are not present. But when you need to take the value of the state.data.city.name key, then city is already undefined. Solved the problem if you save in data not response.data, but immediately response.data.city. But for me this is not an option, since in addition to the name of the city, I still need other keys.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2018-08-19
@deliro

Decided to outsmart yourself?

mutations: {
  GET_DATA(state, response) {
    state.data = response.data;
  }
},

if (response.data) {
  commit("GET_DATA", response.data);
}

Are you savvy?
PS The name of the mutation burns

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question