Trying to retrieve JSON data from an API in VueJS and successfully logging the results, but struggling to render the data on the page. (I

Having recently transitioned from React to VueJs, I encountered a problem where fetching data using axios.get returns a successful response in the console.log. However, when trying to iterate through the array with v-for, nothing is rendered. If you have any suggestions or can point out what I might be doing wrong, it would be greatly appreciated. Here's the code snippet:

    <SignUpForm />
    <h1>Countries List</h1 >
    <div v-for="country in countries" :key="country.name" >
        <p>{{country.name}}</p>
    </div>
</template>

<script>
import SignUpForm from "@/components/SignUpForm.vue";

import axios from 'axios'

export default{
    name: 'SignUpView',
    components:{
      SignUpForm
    }, 
    data(){
      return{
          countries: []
      }    
    },
    async mounted() {
      const {data} = await axios.get('https://gist.githubusercontent.com/keeguon/2310008/raw/bdc2ce1c1e3f28f9cab5b4393c7549f38361be4e/countries.json')
      console.info(data)
      this.countries = data
    }
}

</script>

The axios.get call is made within the mounted(){} lifecycle hook, and then the retrieved data is assigned to an empty array declared in the data(){} function. This allows me to use v-for to iterate through the JSON response in a div.

For visual reference, here's an image of the issue: https://i.sstatic.net/R3U5a.png

Answer №1

Points to Note :

  • The list of countries is provided as a string, however, the v-for directive only works with array inputs.
  • There are a total of 243 objects in the array, but the length of the string representation is 9251.
  • Attempting to convert the string into a JSON object using JSON.parse() results in an error message:
    SyntaxError: Unexpected token n in JSON at position 6
    .

new Vue({
  el: "#app",
  data: {
    countries: []
  },
  methods: {
    getData() {
      var vm = this;
      axios.get("https://gist.githubusercontent.com/keeguon/2310008/raw/bdc2ce1c1e3f28f9cab5b4393c7549f38361be4e/countries.json")
        .then(function(response) {
          console.log(typeof response.data); <---- string
          console.log(response.data.length); <---- actual objects in an array is 243 but this 9251 is a count of characters in a string. 
          console.log(JSON.parse(response.data)); <---- SyntaxError: Unexpected token n in JSON at position 6
        })
        .catch(function(error) {
          alert(error);
        });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<div id="app">
  <button @click="getData">Click to check Api response</button>
</div>

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

The watch functionality is failing to work within a specialized attribute directive that is being utilized within a separate custom element directive

I'm currently working with two directives that handle separate functionalities. I am attempting to utilize the attribute directive within an element directive, but I'm encountering issues with the watch function not working on the attribute direc ...

Most effective method for automatically scrolling down upon page load

Below is the code snippet that I am using: <script type="text/javascript"> window.onload = function () { window.scrollBy(0, 100); } </script> The purpose of this code is to scroll down after the page has fi ...

Troubleshooting: ng-disabled feature is not properly functioning with Bootstrap buttons

I am currently using a combination of bootstrap.js and angular js in my project. The code snippet I have is as follows: //snippet from the controller $scope.isWaiting = true; $scope.promise = $http.get("voluumHandler.php?q=campaigns&filter=traffic-sou ...

Encountering an error stating "ngbCollapse" is not a recognized property of "div" after relocating components to a sub module

Error compiler.js:215 Uncaught Error: Template parse errors: Can't bind to 'ngbCollapse' since it isn't a known property of 'div'. ("][ngbCollapse]="isHidden" In the process of organizing my code, I encountered an issue ...

What is the proper way to create a regex pattern that specifies 'without any spaces'?

I need assistance in creating a regex expression that specifies "and NO whitespaces". I have to incorporate this into the following if statement shown below: $('#postcode').blur(function(){ var postcode = $(this), val = postcode.val(); ...

What is the process for configuring the global warning level in ESLint?

My current setup involves using WebStorm and the ESLint configuration provided by Airbnb. I'm curious if there is a way to have ESLint errors displayed in a more subtle manner instead of the harsh red color, or perhaps make all ESLint rules warnings ...

Issues with Pagination in Laravel and Vue

After clicking on page 2 of the pagination component, the application receives data for page=2, but it does not display on the screen. Instead, the pagination reverts to page 1 and everything starts over. I am utilizing bootstrap-vue as my UI component lib ...

Is it appropriate for a search service to provide a 404 response?

In the world of web development, let's say I have a server-side search feature that is triggered by JavaScript (AJAX). What happens if I search for something like "chewy dragees", and although the server successfully receives the search request, it do ...

Extracting information from a webpage by using Javascript to locate and interact

Seeking a way to retrieve the src attribute from an audio tag dynamically inserted into the DOM by third-party JavaScript without the ability to modify it. The goal is to back up these sounds by capturing their sources on the server side across multiple pa ...

Set up a mouseover function for a <datalist> tag

Currently, I am delving into the world of javascript/jquery and I have set up an input field with a datalist. However, I am encountering a slight hurdle - I am unable to trigger an event when hovering over the datalist once it appears. Although I have man ...

Ways to handle Sessions in Node.js

I'm attempting to utilize a website within node.js. However, the site is prompting me to enable the storage of session cookies. I attempted to set up a cookie-jar, but I couldn't get it to work. Here is a simplified version of the code that is c ...

Can Pinia support using non-root elements as reactive objects?

If you want to understand the basics of reactive properties, check out Pinia's tutorial at . The tutorial focuses on creating a counter that increments without the need for getters and actions. But here's a question: Can you achieve the same sim ...

Creating interactive buttons with CSS and jQuery

As a newcomer to coding, I'm trying my hand at creating two buttons that transition from green to blue with a single click, and eventually incorporating them into a live website. The functionality I'm aiming for includes: Both buttons startin ...

What is the accurate user agent for Windows Phone?

Can someone explain why PHP and JavaScript produce different user agents? Which one is considered the accurate user agent? PHP User Agent Output: <?php print_r($_SERVER['HTTP_USER_AGENT']); ?> User Agent: Mozilla/5.0 (Mobile; Windows Ph ...

Navigating through the complexities of managing asynchronous props and state in React-components

I'm really struggling to understand this concept. My current challenge involves passing asynchronously fetched data as props. The issue is that the props themselves are also asynchronous. Below is a simplified version of the component in question: i ...

Reset jQuery validation when a button is clicked

I need assistance with a form validation issue. I am using jQuery validation methods to validate the controls on my form. However, I am facing difficulties in clearing the validation when clicking on 'cancel'. Below is the code snippet: <scr ...

Sails.js seems to be malfunctioning, as it does not seem to be recognizing the term 'sails'

It seems like I'm encountering an issue with the 'sails' command not being recognized on my Windows 10 system. Despite following all the installation steps, including globally installing Sails.js through npm and ensuring Node is installed, I ...

IE8 triggers automatic download upon receiving JSON response using jQuery

Can you help me make IE8 compatible with this code using jQuery to handle an ajax request that returns data as JSON? $.ajax({ url: formAction, type: 'post', dataType: 'json', data: form, success: ...

Steps for adding a class to an element in VueJS

https://codepen.io/nuzze/pen/yLBqKMY Here's my issue at hand: I currently have the following list stored in my Vue data: { name: 'Camp Nou', id: 'campNou' }, { name: 'Abran cancha', id: 'abranCancha ...

Ways to implement a scrollable v-list component using Vuetify

I have set up a v-list using flex layout, where the v-list expands to fill the remaining space horizontally in a column. However, if the list contains many elements with a total height that exceeds the column's height, the list ends up sticking out of ...