Skip to content

Instantly share code, notes, and snippets.

@miteshmap
Last active February 28, 2020 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miteshmap/d9c95a37ca7076b5b5aeb0be333b2a75 to your computer and use it in GitHub Desktop.
Save miteshmap/d9c95a37ca7076b5b5aeb0be333b2a75 to your computer and use it in GitHub Desktop.
helper method for promoise 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})
}
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment