import React from 'react' import type { GridPreferences, GridPreferencesAdapter } from '../types' /** * This function serves a dual purpose of validating * the payload to ensure a user hasn't incorrectly edited their * values (or maliciously ) * * Once validated, it also provides the correct type */ function validateLoadedPayload(prefs: any): prefs is GridPreferences { if (!('columns' in prefs)) { return false } if (!Array.isArray(prefs.columns)) { return false } return (prefs as GridPreferences).columns.every( (pref) => typeof pref.id === 'string' && (pref.width === null || typeof pref.width === 'number') ) } export function useLocalStoragePreferences( id: string, version = 'v1' ): GridPreferencesAdapter { const load = React.useCallback(() => { try { const data = window.localStorage.getItem(id) if (!data) { return } const { version: incomingVersion, prefs } = JSON.parse(data) if (incomingVersion === version && validateLoadedPayload(prefs)) { return prefs } } catch (error) { // No op - TODO: would like to offer a NODE_ENV based console statement here } }, [version, id]) const save = React.useCallback( (prefs) => { try { window.localStorage.setItem( id, JSON.stringify({ version, prefs }) ) } catch (error) { // No op - TODO: would like to offer a NODE_ENV based console statement here } }, [version, id] ) return React.useMemo(() => ({ load, save }), [load, save]) }