Created
May 8, 2017 15:06
-
-
Save nicinabox/73550176ca27a61851fde63ad82a55d0 to your computer and use it in GitHub Desktop.
React Native common parts
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
const toJSON = r => r.json() | |
const checkStatus = (r) => { | |
if (r.ok) return r | |
return toJSON(r) | |
.then((body) => { | |
let error = new Error(r.statusText) | |
error.body = body | |
error.response = r | |
throw error | |
}) | |
} | |
export const get = (url, options = {}) => { | |
return fetch(url, options).then(checkStatus).then(toJSON) | |
} | |
export const post = (url, body, options = {}) => { | |
options = { | |
headers: { | |
'Content-Type': 'application/json', | |
'Accepts': 'application/json', | |
}, | |
method: 'post', | |
body: JSON.stringify(body), | |
...options, | |
} | |
return fetch(url, options).then(checkStatus).then(toJSON) | |
} |
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 { AsyncStorage } from 'react-native' | |
const serialize = (value) => { | |
return JSON.stringify(value) | |
} | |
const deserialize = (value) => { | |
try { | |
return JSON.parse(value) | |
} catch (e) { | |
return value | |
} | |
} | |
export const getItem = (key) => { | |
return AsyncStorage.getItem(key) | |
.then(deserialize) | |
} | |
export const setItem = (key, value) => { | |
return AsyncStorage.setItem(key, serialize(value)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment