helper method for promoise fetch. which expects promise as an argument.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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