Skip to content
Advertisement

Using Axios instead of fetch for http get requests with Vue App

The following vue app should get some data from a firebase instance using the fetch method and display the data on the page.

UserExperiences.vue

<script>
import SurveyResult from './SurveyResult.vue';
//import axios from 'axios';

export default {
  components: {
    SurveyResult,
  },
  data() {
    return{
      results: []
    }
  },
  methods:{
    loadExperiences() {
      fetch('https://***.firebaseio.com/surveys.json')
      //axios.get('https://***.firebaseio.com/surveys.json')
      .then((response) => {
        if(response.ok) {
          return response.json();
        }
      })
      .then((data) => {
        const results = [];
        for (const id in data) {
          results.push({ 
            id: id, 
            name: data[id].name,
            rating: data[id].rating 
          });
        }
        this.results = results;
      });
    },
  },
};
  // mounted(){
  //   axios.get('https://***.firebaseio.com/surveys.json').then(response => {      
  //     this.results = response.data;
  //   })
  // },
</script>

SurveyResult.vue

<template>
  <li>
    <p>
      <span class="highlight">{{ name }}</span> rated the learning experience
      <span :class="ratingClass">{{ rating }}</span>.
    </p>
  </li>
</template>

<script>
export default {
  props: ['name', 'rating'],
  computed: {
    ratingClass() {
      return 'highlight rating--' + this.rating;
    },
  },
};
</script>

The data renders on the webpage correctly on the webpage using the fetch method. Is there a way to use axios.get instead? I’ve tried using the mounted vue property and it gets the data to appear on a blank screen in a json format, but I want the data to render on the webpage with the stylings and other vue components together.

This is what the page should look like for context: enter image description here

Answer

As long as you do the same transformation of the result (your results.push({ ... }) part), you should get the same result.

You can simplify it like this

axios.get("https://***.firebaseio.com/surveys.json")
  .then(({ data }) => {
    this.results = Object.entries(data).map(([ id, { name, rating } ]) => 
      ({ id, name, rating }));
  });
Advertisement