UNPKG

@mdus/use-localstorage-hook

Version:

React hook to manage localStorage state with sync, reactivity, and cross-tab updates.

2 lines (1 loc) 1.26 kB
import{useState as r,useCallback as e,useEffect as o}from"react";function t(t,a){if(!t||void 0===a)throw new Error("useLocalstorage: storeName and initialData are required.");const l=t?.toString?.(),[n,c]=r(()=>{try{const r=localStorage.getItem(l);return r?JSON.parse(r):a}catch(r){return console.error(`Error reading localStorage key "${l}":`,r),localStorage.removeItem(l),a}}),s=e(r=>{try{localStorage.setItem(l,JSON.stringify(r)),c(r)}catch(r){throw new Error(`useLocalstorage: Failed to set item: ${r.message}`)}},[l]),i=e(()=>{try{localStorage.removeItem(l),c(null)}catch(r){throw new Error(`Error while removing localstorage item: ${r.message}`)}},[l]),g=e(()=>{try{localStorage.clear(),c(null)}catch(r){console.error(`Error clearing localstorage: ${r.message}`)}},[]);return o(()=>{const r=r=>{if(r.key===l)try{null===r.newValue?c(null):c(JSON.parse(r.newValue))}catch(r){console.error(`Error parsing storage event for key "${l}" : ${r}`),c(null)}};return window.addEventListener("storage",r),()=>window.removeEventListener("storage",r)},[l]),o(()=>{try{null===localStorage.getItem(l)&&s(a)}catch(r){console.error(`Error initializing localStorage key "${l}":`,r)}},[l,a,s]),{setStore:s,getStore:n,removeStore:i,clearAllStore:g}}export{t as default};