Discovering a nested key within a JSON object in Vue.js - here's how to do it

Currently, I am attempting to showcase the list of users obtained from my Django API on my VUEjs application.

Here is the data for the User list fetched from the API:

{
  "count": 1,
  "next": null,
  "previous": null,
  "results": [
    {
      "url": "http://localhost:8000/v1/users/1/",
      "username": "admin",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6d7d2dbdfd8f6d3ced7dbc6dad398d5d9db">[email protected]</a>",
      "groups": []
    }
  ]
}

Here is my VUE code snippet:

<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>

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

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

Despite a successful API request and visible data in the network tab, I am facing issues with displaying the data on the webpage. Could there be an issue with how I'm rendering the users or is something crucial missing in my approach?

Seeking guidance as a beginner in VUEjs. Any help is greatly appreciated!

Answer №1

If you only want to iterate through the results in the APIData object:

new Vue({
  el: '#demo',
    data() {
      return {
      APIData: {
        "count": 1,
        "next": null,
        "previous": null,
        "results": [
          {
            "url": "http://localhost:8000/v1/users/1/",
            "username": "admin",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e7e2ebefe8c6e3fee7ebf6eae3a8e5e9eb">[email protected]</a>",
            "groups": []
          },
          {
            "url": "http://localhost:8000/v1/users/1/",
            "username": "user",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3045435542705548515d405c551e535f5d">[email protected]</a>",
            "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>

Answer №2

The issue lies within the v-for loop. I suggest trying the following:

v-for="entry in fetchData.entries"
as "entries" is the variable you are using to represent each element in the array, and not fetchData itself.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we wrap the Vuex store within a Vue plugin's install function?

I developed a plugin that utilizes Vuex for state management. // plugin.js import Vuex from "vuex"; import store from "./store.js"; export default { install(Vue, options) { const storeInstance = new Vuex.Store(store); Vue.pr ...

Updating text in React Native does not reflect changes in context after a state change

I'm facing a challenging issue that I just can't seem to figure out. Here's the dilemma: <TouchableOpacity onPress={() => { if (myContext.value) { alert('true'); //changes myContext.value to false } els ...

Exploring various views in localhost with HTML using AngularJS in asp.net (No MVC)

How do I configure URLs in ASP.NET for AngularJS routing? I've been experimenting with various online examples, but so far I've only managed to get the default route ('/') to display the correct view. It seems like a URL configuration ...

"Incorporating error messages into the Angular callback API for when it fails

Currently engaged in developing an Angular application that interacts with the flickr API. To effectively use the response from flickr, it is necessary to define a jsonFlickrFeed callback function. Check out this link for detailed instructions. The functi ...

Optimal guidelines for logging in

After successfully creating a website using HTML, CSS, and JavaScript, I am now looking to implement a login feature to provide privacy for certain users. I have noticed that some developers use PHP, while others use JS or Node.js for this purpose. However ...

Update the heading from h2 to h1 tag

Is there a way to modify the product names on all product pages, switching them from h2 to h1? I am seeking a solution to change the product names to h1 using custom code. <h2 itemprop="name" class="product_title likeh2">Aspen Ágykeret Bársony S ...

"Embracing Dynamism: Enhancing Vue3 with Dynamic Routing for

Seeking guidance on implementing a dynamic component with Dynamic Routing in Vue3. The goal is to render a component based on the parameter (path named id) from router.ts. In the router.ts file, there is a dynamic parameter called id that needs to be used ...

Ways to repair the error message: "Unable to access property 'clientWidth' of undefined"

Whenever I resize the window, I encounter an error stating "Cannot read property 'clientWidth' of null". It appears to be related to the fact that the ref is null. Do you have any suggestions on how to troubleshoot this issue? import React, { us ...

Guide on destructuring an object to update MySQL with corresponding keys and values

For my project, I am transferring data from a react frontend to an express backend using axios: axios.post('http://localhost/api', {example1: true, example2: false}); Once the data reaches the backend, I am updating a MySQL database with the rec ...

Guide on updating the state using a computed property in Vue.js

I'm facing an issue with updating my state data within a computed property named computedFirstName. Currently, the state changes on every letter I type, but I only want it to update when I click the submit button and call the update method. Below is ...

Looking for a simple method to convert JSON object properties into an array?

Is there a simple method for extracting only the values of the properties within the results object in the given JSON data? let jsonData = {"success":true, "msg":["Clutch successfully updated."], "results":{"count_id":2, ...

Preventing Redundant Translation Keys in Nuxt i18n

Currently, I am utilizing Nuxt along with Nuxt i18n for component translations: <template> <div>{{ $t("Hello world") }}</div> </template> <i18n lang="yaml"> fr: Hello world: Bonjour le monde </i18n& ...

I'm curious why my background generator is only altering a portion of the background instead of the entire thing

I've been attempting to create a JavaScript random background changer, but I'm encountering some challenges. The main issue is that instead of changing the entire page's background, it only alters a strip of it. Additionally, I'm curiou ...

Clicking on a link with an onclick method renders selenium ineffective in producing any action

The specified element is: <a href="#" onclick="submitViaAjax(null, url);return false;">Add</a> After using element.click() to try clicking the link, the onclick method fails to execute. Is there a way to ensure the method is executed success ...

What steps can I take to avoid unintentionally populating this object with undefined values?

This issue occurs when the variable level is initialized with the value 'undefined'. Although this code functions correctly in JavaScript, it encounters problems when using TypeScript. interface Find { level?: string; } let find: Find = {}; ...

The express app is configured to send a 301 status code when Supertest is used, and it is

Hello, I am currently utilizing supertest to test the functionality of my Node.js express server application. My goal is to accomplish the following: let request = require('supertest'); let app = require('./server.js'); request(app). ...

Analyzing an array of objects

Is there a way to filter an array of objects to only include elements that have 'text' containing 'ild'? For example, consider the following array: public data: any[] = [ { treeViewKey:0, id: 1, text: 'Root Node 1&a ...

Implementing conditional logic using v-if and v-else statements

I am currently diving into the world of vue.js! I have enrolled in a course on Udemy to expand my knowledge. While experimenting with basic conditional statements, specifically if-else statements, I encountered an issue. Despite following the instruction ...

Embracing JQuery for Frontend Development with Node.js

I'm currently enhancing my node.js skills by utilizing express, and I've encountered a situation that is causing me some confusion. Essentially, when a user requests a webpage and the backend sends them the HTML page, how can I incorporate a Java ...

Attempting to modify the environmental variable within node.js via the terminal proves to be a fruitless endeavor as the value consistently remains undefined

Recently, I entered the world of backend development and came across this JS code utilizing express: const express = require('express'); const app = express(); const port = process.env.PORT || '3000'; app.listen(port, ()=> console.lo ...