Promise fetcher

28 February 2020 — Written by Mitesh Patel
#javascript#investment

Helper method for promise fetch. which expects promise as an argument

// Helper method to handle error and expact only error or result.
export const createFetcher = promiseFunc => {
return {
read: arg => {
try {
return promiseFunc(arg)
.then(response => {
if (!response) {
return {error: 'error!'};
}
if (typeof response.data !== 'object') {
return {error: 'error!'};
}
if (!response.data.error && response.data.error) {
console.error(cart_result.error_message);
return {error: 'error!'};
}
return response.data;
},
reject => {
return {error: reject};
});
}
catch (error) {
return new Promise(
resolve => resolve({error: error})
);
}
}
}
}
// API promise
export const fetchApiCall = arg => {
const GET_URL = `https://api.com/some/fake/request/${arg.id}/${arg.name}`;
return Axios.get(GET_URL);
};
// Usage:
makeApiCall = () => {
const apiFetcher = createFetcher(
fetchApiCall
);
let apirequest = apiFetcher.read({
id: 1,
name: 'something'
});
apirequest.then(
response => {
if (typeof response.error === 'undefined') {
this.setState({updatestate})
}
}
);
}

Copyright © 2022 Mitesh Patel. Built with Gatsby