Skip to content

Instantly share code, notes, and snippets.

@gauravsoti1
Last active May 6, 2020 07:01
Show Gist options
  • Save gauravsoti1/4a09ce8c5b5795f533054d77274a64a7 to your computer and use it in GitHub Desktop.
Save gauravsoti1/4a09ce8c5b5795f533054d77274a64a7 to your computer and use it in GitHub Desktop.
A simple and easy to use wrapper over fetch
import { stringify } from 'query-string';
export const sendRequest = ({
url,
method,
useCredentials=false,
body,
headers = {},
queryParams = {}
}) => {
const options = {
method: method,
headers: new Headers({ 'content-type': 'application/json', ...headers }),// by default setting the content-type to be json type
body: body ? JSON.stringify(body) : null
};
if (useCredentials) options.credentials = "include";
if (queryParams) {
url = `${url}?${stringify(queryParams)}`;
}
return fetch(url, options).then(res => {
if (res.ok) {
return res.json();
} else {
return res.json().then(function(json) {
// to be able to access error status when you catch the error
return Promise.reject({
status: res.status,
ok: false,
message: json.message,
body: json
});
});
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment