Search code examples
javascriptvue.jsaxiosvuejs3rapidapi

Data API not appear using Vue JS (Rapidapi)


I'm learning how to use an API with VueJS. I took open source API data on Rapidapi.

I tried with Postman by entering the link https://covid-19-data.p.rapidapi.com/report/country/name?name=Italy&date=2020-04-01, and got a response.

But when trying in VueJS, the data does not appear. Is there any miss in my looping?

Here is a hosted codesandbox of my code: https://codesandbox.io/s/nice-rain-45j6y

<template>
  <div v-for="post in posts" :key="post.id">
    {{ post.country }}
    {{ post.confirmed }}
  </div>
</template>

<script>
export default {
  data() {
     return {}
  },
  computed: {
    posts() {
        return this.$store.state.posts
    }
  },
  mounted() {
    this.$store.dispatch("loadPosts");
  }
};
</script>
import axios from 'axios'

const options = {
    method: 'GET',
    url: 'https://covid-19-data.p.rapidapi.com/country',
    params: {name: 'italy'},
    headers: {
      'x-rapidapi-key': '1031599022msh37c84da8c4e9b0ap1047d6jsn4d6475b64dc7',
      'x-rapidapi-host': 'covid-19-data.p.rapidapi.com'
    }
  };

const covid = {
    state: () => ({
      posts: []
    }),
    mutations:{
      setPosts(state, components){
         state.posts = posts
      }
    },
    actions: {
      loadPosts({ commit }) {
        axios.request(options)
        .then(response => {
            commit('setPosts', response.data)
            console.log(response.data)
        })
        .catch(function (error) {
            console.error(error);
        });
      }
    },

}

export default covid;

The response that I get with my console.log(response.data) is the following

enter image description here


Solution

  • Thanks to your codesandbox, I achieved to display it properly with this

    <template>
      <div>
        <div v-for="post in posts" :key="post.longitude"> <!-- be careful here, you had a longatitude typo here -->
          <div>country: {{ post.country }}</div>
          <div>code: {{ post.code }}</div>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {}
      },
      computed: {
        posts() {
          return this.$store.state.covid.posts
        },
      },
      mounted() {
        this.$store.dispatch('loadPosts')
      },
    }
    </script>
    

    The main error was essentially in the covid.js file actually

    mutations: {
      setPosts(state, posts) { // was components here, but should be posts as the 2nd argument
        state.posts = posts;
      }
    },