JimmyOppa
JimmyOppa

Reputation: 67

How to find nested key in the json object in vuejs

I am trying to display the users from the user list which I am getting from my Django API on my VUEjs app.

My User list data from API:

{
  "count": 1,
  "next": null,
  "previous": null,
  "results": [
    {
      "url": "http://localhost:8000/v1/users/1/",
      "username": "admin",
      "email": "[email protected]",
      "groups": []
    }
  ]
}

My VUE code:

<template>
    <div>
        <h1> Users </h1>
        <div v-for="results in APIData" :result="results" :key="results.username">
            <h5>{{ result.username }}</h5>
            <p>{{ result.email }}</p>
        </div>
    </div>
</template>

<script>
import { getAPI } from '../axios-api';
import { mapState } from 'vuex';

export default {
    name: 'Users',
    computed: mapState(['APIData']),
    created() {
        getAPI.get('/v1/users/', { headers: { Authorization: 'Bearer ' + this.$store.state.accessToken } })
        .then(response => {
            this.$store.state.APIData = response.data
        })
        .catch(error => {
            console.log(error)
        })
    }
}
</script>

For some reason, the data is not getting displayed on the webpage even though I can see my API request is successful and I can see the data in my network tab. Is the way displaying the users right? or am I missing something?

I'm new to VUEjs, can someone help?

Upvotes: 1

Views: 429

Answers (2)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23480

If you want to loop only thru results in APIData :

new Vue({
  el: '#demo',
    data() {
      return {
      APIData: {
        "count": 1,
        "next": null,
        "previous": null,
        "results": [
          {
            "url": "http://localhost:8000/v1/users/1/",
            "username": "admin",
            "email": "[email protected]",
            "groups": []
          },
          {
            "url": "http://localhost:8000/v1/users/1/",
            "username": "user",
            "email": "[email protected]",
            "groups": []
          }
        ]
      }
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <template>
    <div>
      <h1> Users </h1>
      <div v-for="result in APIData.results" :key="result.username">
        <h5>{{ result.username }}</h5>
        <p>{{ result.email }}</p>
      </div>
    </div>
  </template>
</div>

Upvotes: 1

Diego Castro
Diego Castro

Reputation: 1

The problem is in the v-for, you might try: v-for="results in APIData.results" since "results" is not an accessor, is the name that you are assigning to each value inside the array, and APIData is not an array.

Upvotes: 0

Related Questions