kasp3rsky
kasp3rsky

Reputation: 167

How to fetch data in Vue 3?

I don't know how to fetch data with Vue 3? I created one action and with this action I am calling endpoint (https://api.openbrewerydb.org/breweries/5494). I didn't get response data.

Endpoint:

import { createStore } from 'vuex'

export default createStore({
  state: {
  },
  mutations: {
  },
  actions: {
    async getData() {
      await fetch('https://api.openbrewerydb.org/breweries/5494', {
        method: 'get',
        headers: { 'Content-type': 'application/json' },
      }).then((response) => {
        if (!response.ok) {
          throw Error(response.statusText);
        }
        console.log('response: ', response)
      }).catch((error) => {
        console.log('Looks like there was a problem: \n', error);
      });
    }
  },
  modules: {
  }
})

Vue component:

<template>
  <div @click="loadData">Load Data</div>
</template>

<script>
import { useStore } from 'vuex'

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },

  setup () {
    const store = useStore()

    const loadData = () => {
      store.dispatch('getData')
    }

    return { loadData }
  }
}
</script>

As a response I didn't get anything but I should get:

{"id":5494,"name":"MadTree Brewing","brewery_type":"regional","street":"3301 Madison Rd","address_2":null,"address_3":null,"city":"Cincinnati","state":"Ohio","county_province":null,"postal_code":"45209-1132","country":"United States","longitude":"-84.4239715","latitude":"39.1563725","phone":"5138368733","website_url":"http://www.madtreebrewing.com","updated_at":"2018-08-24T15:44:22.281Z","created_at":"2018-07-24T01:34:01.620Z"}

Upvotes: 5

Views: 18597

Answers (3)

VAhid
VAhid

Reputation: 92

First you must install a package like axios Then create an object from axios and call the API

import axios from "axios";
export default {
  setup() {
    function getUsers() {
      axios.get("https://jsonplaceholder.typicode.com/users")
        .then(function (response) {
          // handle success
          console.log(response.data);
        })
        .catch(function (error) {
          // handle error
          console.log(error);
        });
      getUsers();
    }
    return { getUsers };
  },
};

Upvotes: -1

DaveL17
DaveL17

Reputation: 2013

This answer Should be the accepted answer.

If readers landed here while working through the introductory examples on the Vue.js website, Adarsh's code can be adapted thusly (for Vue.js 3):

<div id="beer">
  {{ message }}
</div>

const Breweries = {
    data() {
        return {
            message: ""
        }},
    mounted() {
        fetch('https://api.openbrewerydb.org/breweries/', {
            headers: { 'Content-type': 'application/json' },
        }).then(res=>res.json()).then((response) => {
            this.message = response;
        }).catch( (error) => {
            this.message = error;
        });
    }
}
Vue.createApp(Breweries).mount('#beer')

Upvotes: 0

Adarsh Mohan
Adarsh Mohan

Reputation: 1384

You need to make the data to json

.then(res=>res.json())

this will do the trick for you.

const getData = () => {
  fetch('https://api.openbrewerydb.org/breweries/5494', {
    headers: { 'Content-type': 'application/json' },
  }).then(res=>res.json()).then((response) => {
    console.log({ response })
  }).catch((error) => {
    console.log('Looks like there was a problem: \n', error);
  });
}

getData();

If the response fails, it will surely get you to catch.

Upvotes: 3

Related Questions