Skip to content

Instantly share code, notes, and snippets.

@cameck
Created September 8, 2019 23:06
Show Gist options
  • Save cameck/c682a9f62627a48a886124000a6504e8 to your computer and use it in GitHub Desktop.
Save cameck/c682a9f62627a48a886124000a6504e8 to your computer and use it in GitHub Desktop.
An API Call helper function for native fetch calls. Abstracts away a lot of common boilerplate in error handling and JSON parsing. Comments are welcome
/**
* Callback for passing back result data.
* @callback updateCallback
* @param {string} result - A success or error string
*/
/**
* Callback to run after all is done.
* @callback finalCallback
*/
/**
* A function that handles parsing of fetch requests
* @todo add support for better error messaging on non-json responses
* @param {object} options - All the fun stuff.
* @param {function} options.fetch - The http fetch call
* @param {updateCallback} options.successCb - The function to call on success.
* @param {updateCallback} options.errorCb - The function to call on error.
* @param {finalCallback} options.finallyCb - The function to be called when all is done.
* @example
* apiCall({
* fetch: () => fetch('https://bananas.com?id=1'),
* updateCallback: banana => this.setState({ banana }),
* errorCallback: error => this.setState({ error }),
* finallyCb: () => this.setState({ loading: false })
* })
*/
export const apiCall = async ({ fetch, successCb, errorCb, finallyCb }) => {
try {
const resp = await fetch();
const contentType = resp.headers && resp.headers.get('content-type');
if (resp.ok || (contentType && contentType.includes('application/json'))) {
const json = await resp.json();
json.error
? errorCb(`ERROR: ${json.error.message}. CODE: ${json.error.code}`)
: successCb(json);
} else {
throw new Error(`${resp.statusText}:${resp.status}`);
}
} catch (error) {
errorCb(error.message || error);
} finally {
finallyCb && finallyCb();
}
};
@cameck
Copy link
Author

cameck commented Sep 8, 2019

The example, is built with the idea of it living in something like React's componentDidMount, but should be able to be used most places.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment