Home > database >  Using vuex/vuejs, How to call api from external '.js' file in Vuejs?
Using vuex/vuejs, How to call api from external '.js' file in Vuejs?

Time:02-04

I am calling the api from my external.js file and then i am calling it inside of my component using the v-for to display the required data. During this process, I am unable to call the api. Everytime i am getting error as axios defined but never used.

This is my endpoint url, Which i want to call inside of data.js file:- https://randomuser.me/api/

Issue when trying to call the api from external.js file in Vuejs

Code working:- https://codesandbox.io/s/blissful-northcutt-wze8i?file=/src/components/data.js

data.js

export default {
  methods: {
    mydata() {
      axios.get("https://randomuser.me/api/").then((response) => this.response);
    }
  }
};

HelloWorld.vue

<template>
  <div>
    <div v-for="list in lists" :key="list.id">
      {{ list.name }}<br />{{ list.location }}
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { mydata } from "./data";
export default {
  name: "HelloWorld",
  data() {
    return {
      lists: mydata,
    };
  },
};
</script>

CodePudding user response:

You can call the endpoint API using Axios like this.

<template>
  <div>
    <div v-for="user in users" :key="user .id">
      {{ user.name }}<br />{{ user.username}}
    </div>
  </div>
</template>


<script>
import axios from "axios";
// import { mydata } from "./data";
export default {
  name: "HelloWorld",
  data() {
    return {
      // lists: mydata,
      users: []
    };
  },
  mounted () {
   axios
  .get('https://jsonplaceholder.typicode.com/users/2')
  .then(response => (this.users = response))
  .catch(error => console.log(error))
  }
};
</script>

CodePudding user response:

First, you should export function in simpliest way:

import axios from "axios";

export const mydata = () => {
  return axios.get("https://randomuser.me/api/").then((response) => response);
}

Remember to import axios in your external js file because you use it there, not in component file.

Second, your API will return Promise, so you have to wait for result - you can do it by calling API in mounted method and filling property list when it will be ready.

<template>
  <div>
    <div v-for="list in lists" :key="list.id.value">
      {{ list.name }}<br />{{ list.location }}
    </div>
  </div>
</template>

<script>
import { mydata } from "./data";

export default {
  name: "HelloWorld",
  data() {
    return {
      lists: [],
    };
  },
  mounted() {
    mydata().then(r => { this.lists = r.data.results });
  }
};
</script>

Last but not least, an object returnde from api is little different then you expect, so I have aligned html code for real case.

  •  Tags:  
  • Related