Reputation: 3
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
Upvotes: 0
Views: 2740
Reputation: 30
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;
Upvotes: 0
Reputation: 11
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
Upvotes: 1