Search code examples
javascriptapivue.jsmustache

Vue: Access values over api (nested)


Hi Stackoverflow Community,

In my template I try to show data which I receiver over an api call. When I log the api get response this is what I receive: enter image description here

Now I try to show the data in location with the following code: {{ userdetails.location.location_name }}

My script looks like this:

data() {
    return {
      userdetails: [],
    };
  },
  methods: {
    getUserData() {
      DataService.getUserById()
        .then((response) => {
          this.userdetails = response.data;
          console.log(response);
        }) 

...

  created() {
    this.getUserData();
  },

The strange thing is, I can see the location_name in my application. But I also receive an error:enter image description here

I think I made somewhere a mistake, but I can't find it. Do you have any ideas what I am doing wrong?

Thank you in advance for all your tipps!


Solution

  • At the start, when the template tries to access userdetails.location.location_name, it is an empty list, so you will see the error. Only once the DataService updated userdetails will the nested properties exist.

    The easiest way to prevent this is to start out with userdetails as something which is 'falsey' and then use v-if to determine whether to render:

    <div v-if="userdetails">{{userdetails.location.location_name}}</div>
    
    data() {
    return {
      userdetails: undefined,
    };
    

    },

    Note however that if your DataService could ever return a dict which doesn't have the location property, you will need to do more testing in v-if to determine if it can be rendered.