Created
March 2, 2017 09:46
-
-
Save alfian0/990ea1fb04a88a9d789bf6a2e34ddf31 to your computer and use it in GitHub Desktop.
[React Native] - Simplify React Native Fetch
This file contains hidden or 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
| class Api { | |
| static headers() { | |
| return { | |
| Accept: 'application/json', | |
| 'Content-Type': 'application/json', | |
| dataType: 'json', | |
| }; | |
| } | |
| static get(route) { | |
| return this.xhr(route, null, 'GET'); | |
| } | |
| static put(route, params) { | |
| return this.xhr(route, params, 'PUT'); | |
| } | |
| static post(route, params) { | |
| return this.xhr(route, params, 'POST'); | |
| } | |
| static delete(route, params) { | |
| return this.xhr(route, params, 'DELETE'); | |
| } | |
| static xhr(route, params, verb) { | |
| const host = 'http://www.recipepuppy.com'; | |
| const url = `${host}${route}`; | |
| const options = Object.assign( | |
| { method: verb }, | |
| params ? { body: JSON.stringify(params) } : null | |
| ); | |
| options.headers = Api.headers(); | |
| return fetch(url, options).then((resp) => { | |
| const json = resp.json(); | |
| if (resp.ok) { | |
| return json; | |
| } | |
| return json.then((err) => { throw err; }); | |
| }) | |
| .then(json => json.results); | |
| } | |
| } | |
| export default Api; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment