Last active
May 6, 2020 07:01
-
-
Save gauravsoti1/4a09ce8c5b5795f533054d77274a64a7 to your computer and use it in GitHub Desktop.
A simple and easy to use wrapper over fetch
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
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