Skip to content

Instantly share code, notes, and snippets.

@putuyoga
Created July 25, 2018 03:28
Show Gist options
  • Save putuyoga/abdc0e8c1ddd0c9ba05d721a148ba657 to your computer and use it in GitHub Desktop.
Save putuyoga/abdc0e8c1ddd0c9ba05d721a148ba657 to your computer and use it in GitHub Desktop.
React Native Custom Storage for Android
import RNFetchBlob from 'react-native-fetch-blob';
const DocumentDir = RNFetchBlob.fs.dirs.DocumentDir;
const storagePath = `${DocumentDir}/persistStore`;
const encoding = 'utf8';
const toFileName = name => (
name.split(':').join('-')
);
const fromFileName = name => (
name.split('-').join(':')
);
const pathForKey = key => (
`${storagePath}/${toFileName(key)}`
);
const handleError = callback => (error) => {
if (callback) callback(error);
};
const getItem = async (key, callback) => {
try {
const location = pathForKey(toFileName(key));
const data = await RNFetchBlob.fs.readFile(location, encoding);
if (callback) callback(null, data);
return data;
} catch (error) {
handleError(callback)(error);
return null;
}
};
const setItem = async (key, value, callback) => {
try {
await RNFetchBlob.fs.writeFile(pathForKey(key), value, encoding);
if (callback) callback();
} catch (error) {
handleError(callback)(error);
}
};
const removeItem = async (key, callback) => {
try {
const location = pathForKey(toFileName(key));
await RNFetchBlob.fs.unlink(location);
if (callback) callback();
} catch (error) {
handleError(callback)(error);
}
};
const getAllKeys = async (callback) => {
try {
const isExist = RNFetchBlob.fs.exists(storagePath);
if (!isExist) return null;
await RNFetchBlob.fs.mkdir(storagePath);
const files = await RNFetchBlob.fs.ls(storagePath);
const results = files.map(file => fromFileName(file));
if (callback) callback(null, files);
return results;
} catch (error) {
handleError(callback)(error);
return null;
}
};
export default {
setItem,
getItem,
removeItem,
getAllKeys
};
import { AsyncStorage } from 'react-native';
import CustomStorage from './CustomStorage';
// AsyncStorage isn't works on the android with debugger attached
// This is a well known issue, even on the latest react-native it still happens
// Many areas depend on AsyncStorage API, which is we are doomed now lol
// Best we can do is on Development Mode, instead use AsyncStorage
// we replace it with our custom storage service instead
// -----------------------------------------------------------
// Further reference: https://github.com/facebook/react-native/issues/12830
const SelectedStorage = __DEV__
? CustomStorage
: AsyncStorage;
export default SelectedStorage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment