Vue.js calling an async function from external js file - javascript

I am trying to create a .js file where I have a couple of my async calls.
I set up the file, but am not getting any results when I call my method.
This is all new to me to call from a .js file, so not sure what I am doing wrong.
Here is my inventory.js fileimport axios from "axios";
let getInventories = async () => {
const result = await axios
.get("/inventories")
.catch((error) => console.log(error));
// this.inventoryArray = result.data;
}
export {getInventories}
Here is the call from my Inventory.vue file
import axios from "axios";
import { bus } from "../app";
import {getInventories} from './inventory';
export default {
mounted() {
let temp = getInventories();
debugger;
},
}
temp not returning anything. I add await in from of getInventories but get an error

You're missing to return the result :
let getInventories = async () => {
try{
const result = await axios
.get("/inventories")
return result.data;
} catch(error){
console.log(error);
return null;
};
}
export {getInventories}

Related

Vue 3 using function inside setup

I am doing a simple app and I am using mock-json-server to simulate http request.
I have defined a function to get the info I need :
import { ref } from 'vue'
const getScores = () => {
const scoringPass = ref([])
const error = ref(null)
const load = async () => {
try {
let data = await fetch('http://localhost:8000/scores', {
method: 'get',
headers: {
'content-type': 'application/json'
}})
if (!data.ok) {
throw Error('no data available')
}
scoringPass.value = await data.json()
console.log(scoringPass.value)
} catch (err) {
error.value = err.message
console.log(error.value)
}
}
return { scoringPass, error, load }
}
export default getScores
And I call it in the setup function of my component :
<script lang="ts">
import { defineComponent } from 'vue'
import Pass from '#/components/Pass.vue'
import getScores from '../composables/getScores.js'
export default defineComponent({
setup() {
const numeroDossier = '25020230955000004'
const { scoringPass, error, load } = getScores()
load()
return { numeroDossier, scoringPass, error }
},
components: {
Pass,
},
})
</script>
In the console.log(scoringPass.value) in the function, I can see the data. but the load() function in the setup part does not work and I can't figure out why. It is called though, but I can't get the data.
When I do console.log(load()), I get :
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined
Any help appreciated.
Cheers.
load() is async, so its return value is a Promise. You have to await the call to get the underlying data. However, load() doesn't actually return anything, so you still wouldn't see any data. If you want load() to provide the initial value of scoringPass, load() should return that:
const load = async () => {
try {
⋮
return scoringPass.value
} catch (err) {
⋮
return null
}
}
To get the result of load(), you can wrap the call in an async function to await the call; or chain a .then() callback:
export default defineComponent({
setup() {
⋮
const logLoadResults = async () => console.log(await load())
logLoadResults()
// or
load().then(results => console.log(results))
}
})
Don't mark setup() as async because that would make your component an async component, requiring a <Suspense> in a parent component to render it.

How to wait for axios function to return value when in service class

I want to structure my application with some sort of service class, but whenever I extract my axios calls from the page, then the axios function seems to return "undefined".
My page looks like this. The signin function is called when the user hits the button. When I put the axios call in the page like this, everything works fine. The usestate is updated and displays.
export default function AccountPage() {
const [signinResponse, setSigninResponse] = useState();
async function signin() {
await axios
.get(
`...url...`
)
.then((res) => {
setSigninResponse(res)
});
}
...
However, when I take the axios function and move it to a service class like this
import axios from "axios";
export async function tableauSignin() {
await axios
.get(
`...url...`
)
.then((res) => {
console.log(res);
return res;
});
}
and then import and make the call like this
import { tableauSignin } from "../services/tableau-online.service";
...
export default function AccountPage() {
const [signinResponse, setSigninResponse] = useState();
async function signin() {
const r = await tableauSignin();
setSigninResponse(r);
console.log(r);
}
...
the log from the service class is good but the log on the account page is undefined.
As #RobinZigmond mentioned in comment. The following solution will work but it's a needless.
it's a needless verbose way of just doing export function
tableauSignin() { return axios.get(url).then(response =>
response.data) }.
export async function tableauSignin() {
return await axios.get(url).then(response => response.data)
}
This Solution may be more useful
const getData = async () => {
let res = await axios.get("url");
let { data } = res.data; //or res
return data;
};
You can also import this way
var response = await getData();

How can i seperate my fetch request to another file in react js

am using react and trying access the promise object which is defined in one file (service file) from another file (class component) .but when am importing the getData to another file ,it gives me undefined.
Can someone help me out in this.
service.js file
export const getData=()=>{
fetch('url', {
method:'Get',
})
.then(data=> {
return data.json()
})
}
component file
import {getData} from '../Service'
console.log(getData()) //gives undefine
you should return data in function getData
service.js file
export const getData=()=>{
return fetch('url', { // add return here
method:'Get',
})
.then(data=> {
return data.json()
})
}
component file
import {getData} from '../Service'
console.log(getData()) //gives undefine
component file
let getFetch = async () => {
const url = "https://jsonplaceholder.typicode.com/todos";
let res = await getRequestData(url);
console.log(res)
}
getFetch();
service.js
const getRequestData = async (url) => {
let resData = await fetch(url)
.then( res => res.json() )
.then( async (result) => {
return result
} ,
(error) => {
return error
});
return resData;
}
export default getRequestData;

Is there a way to store fetched API data in a global variable?

I want to fetch data from an API and store that into a variable, and export that variable to other modules for reusability.
However, I can't seem to figure out how to reuse the data..
// getData.js
let data;
async function getData(){
let fetchedData = await fetch('someURL').then(value => value.json());
data = fetchedData;
}
export { data };
// otherModule.js
import { data } from './getData.js';
console.log(data);
If I do this, I know that data will not actually wait for the promise to resolve/reject and print out empty.
So, is there a way to store the fetched data in a variable that can be exported to other modules?
// getData.js
async function getData(){
const response = await fetch('someURL');
const data = await response.json();
return data;
}
export { getData };
// otherModule.js
import { getData } from './getData.js';
getData().then((data) => {
console.log(data);
})
You seem to be looking for
// getData.js
export const dataPromise = fetch('someURL').then(value => value.json());
// otherModule.js
import { dataPromise } from './getData.js';
dataPromise.then(data => {
console.log(data);
});

How to import a function into a Vue component?

I have a js file named axios.js. Inside this file:
import axios from 'axios';
export function axiosGet (url, data, loading) {
axios.get(url, data, loading)
.then((response) => {
loading = false;
data = response.data;
})
.catch(error => console.log(error))
.finally(() => {
loading = true;
})
}
I have a Vue component where I import this function:
import {axiosGet} from '../axios.js'
mounted() {
axiosGet('https://jsonplaceholder.typicode.com/users', this.APIusers, this.isLoading);
}
where APIusers and isLoading are in data.
I get no error but it's not working.
What should I change to make it work?
Your problem is not related to importing function in vue component.
You have to change calling api function to this:
async mounted() {
this.isLoading = true;
const res = await axiosGet("https://jsonplaceholder.typicode.com/users");
if (res) {
this.APIusers = res;
}
this.isLoading = false;
}
and api function:
export async function axiosGet(url) {
try {
const response = await axios.get(url);
return response.data;
} catch (err) {
console.log(err);
}
}
here is working deme: https://codesandbox.io/s/hopeful-murdock-xqpws

Categories