Skip to content

Instantly share code, notes, and snippets.

@nicinabox
Created May 8, 2017 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicinabox/73550176ca27a61851fde63ad82a55d0 to your computer and use it in GitHub Desktop.
Save nicinabox/73550176ca27a61851fde63ad82a55d0 to your computer and use it in GitHub Desktop.
React Native common parts
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)
}
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