CoderLee
CoderLee

Reputation: 3479

How to load data into Vue component

I have an API endpoint for https on localhost that's serving raw json data like so:

[{"day":"Monday","hours":43,"date":"2019-12-23T14:38:08.2112312-05:00"},{"day":"Tuesday","hours":36,"date":"2019-12-24T14:38:08.2130238-05:00"},{"day":"Wednesday","hours":39,"date":"2019-12-25T14:38:08.2130318-05:00"},{"day":"Thursday","hours":34,"date":"2019-12-26T14:38:08.2130329-05:00"},{"day":"Friday","hours":42,"date":"2019-12-27T14:38:08.2130338-05:00"}]

What I don't understand is why VUE.js is failing with a "TypeError: "NetworkError when attempting to fetch resource." JSON is being surved for localhost use, and cors has been enabled. Any get request from postman, browser, curl, etc works just fine. It's only failing when VUE.js makes the fetch() call.

The VUE component:

<template>
  <div class="container">
    <LineChart v-if="loaded" :chartdata="chartdata" :options="options" />
  </div>
</template>

<script>
import LineChart from './LineChart.vue';

export default {
  name: 'LineChartContainer',
  components: { LineChart },
  data: () => ({
    loaded: false,
    chartdata: null,
  }),
  async mounted() {
    this.loaded = false;
    try {
      const { daysWorked } = await fetch(
        'https://localhost:5001/api/timeworked',
      );
      console.log('days worked data:', daysWorked);
      this.chartdata = daysWorked;
      this.loaded = true;
    } catch (e) {
      console.error("Couldn't access data:", e);
    }
  },
};
</script>

Any thoughts, advice, or tips appreciated!

Upvotes: 0

Views: 164

Answers (1)

Ivan Klochkov
Ivan Klochkov

Reputation: 702

It's not a problem with Vue. It's a problem with the way you fetch.

Take a look at https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API and https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

try

...
const { daysWorked } = await fetch('https://localhost:5001/api/timeworked')
                                 .then(r=>r.json());
...

this should help.

Upvotes: 1

Related Questions