beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
58 lines (57 loc) • 2.18 kB
JavaScript
import { useCallback, useState } from 'react';
import safelyParseJson from '../shared/safelyParseJson';
import isClient from '../shared/isClient';
import isAPISupported from '../shared/isAPISupported';
import isDevelopment from '../shared/isDevelopment';
import noop from '../shared/noop';
import warnOnce from '../shared/warnOnce';
/**
* A utility to quickly create hooks to access both Session Storage and Local Storage
*/
const createStorageHook = (type) => {
const storageName = `${type}Storage`;
if (isClient && !isAPISupported(storageName)) {
warnOnce(`${storageName} is not supported`);
}
/**
* the hook
*/
return function useStorageCreatedHook(storageKey, defaultValue) {
if (!isClient) {
if (isDevelopment) {
warnOnce(`Please be aware that ${storageName} could not be available during SSR`);
}
return [JSON.stringify(defaultValue), noop];
}
const storage = (window)[storageName];
const safelySetStorage = useCallback((valueToStore) => {
try {
storage.setItem(storageKey, valueToStore);
// eslint-disable-next-line no-empty
}
catch (e) {
}
}, [storage, storageKey]);
const [storedValue, setStoredValue] = useState(() => {
var _a;
let valueToStore;
try {
valueToStore = (_a = storage.getItem(storageKey)) !== null && _a !== void 0 ? _a : JSON.stringify(defaultValue);
}
catch (e) {
valueToStore = JSON.stringify(defaultValue);
}
safelySetStorage(valueToStore);
return safelyParseJson(valueToStore);
});
const setValue = useCallback((value) => {
setStoredValue((current) => {
const valueToStore = value instanceof Function ? value(current) : value;
safelySetStorage(JSON.stringify(valueToStore));
return valueToStore;
});
}, [safelySetStorage]);
return [storedValue, setValue];
};
};
export default createStorageHook;