Skip to content

Instantly share code, notes, and snippets.

@vuongngo
Created January 9, 2020 07:33
Show Gist options
  • Save vuongngo/669e71199ac8742fecbf278e01339f26 to your computer and use it in GitHub Desktop.
Save vuongngo/669e71199ac8742fecbf278e01339f26 to your computer and use it in GitHub Desktop.
const createMigration = (opts, data) => {
return new Promise((resolve, reject) => {
const key = `${opts.key}-version`;
localforage.getItem(key, (err, version) => {
if (version !== opts.version) {
data = opts.migrate(data);
localforage.setItem(opts.key, rehydrate(data), (err) => {
if (err) return reject(err);
localforage.setItem(key, opts.version, (err) => {
if (err) return reject(err);
return resolve(data);
});
})
} else {
resolve(data);
}
});
});
};
const config = {
key: '@session',
version: 1,
migrate: (state) => {
return {...state};
}
};
const useStorage = (state, setState) => {
const [rehydrated, setRehydrated] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
localforage.getItem(config.key, (err, value) => {
if (err) {
setRehydrated(true);
return setError(err);
}
// Migrate persisted data
const restoredValue = rehydrated(value);
if (typeof config.migrate === 'function') {
createMigration(config, restoredValue)
.then(data => setState(data))
.then(() => setRehydrated(true));
} else {
setState(restoredValue);
setRehydrated(true);
}
});
}, []);
useEffect(() => {
if (isNil(state) || isEmpty(state)) {
localforage.removeItem(config.key);
}
localforage.setItem(config.key, hydrate(state));
}, [state]);
return {
rehydrated,
error,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment