All files / src/hooks usePersistentState.ts

88.88% Statements 8/9
100% Branches 2/2
100% Functions 2/2
88.88% Lines 8/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26            136x     136x   136x         136x 136x 10x 10x     136x      
import { useState } from "react";
 
function usePersistentState<T>(
  key: string,
  defaultValue: T,
): [T, (value: T) => void] {
  const storedState = localStorage.getItem(key);
  let initialState: T;
 
  try {
    // Attempt to parse the stored state, fall back to defaultValue if it fails
    initialState = storedState ? JSON.parse(storedState) : defaultValue;
  } catch (error) {
    initialState = defaultValue; // Fallback to default value if JSON parsing fails
  }
 
  const [state, setState] = useState<T>(initialState);
  const setPersistentState = (value: T) => {
    setState(value);
    localStorage.setItem(key, JSON.stringify(value));
  };
 
  return [state, setPersistentState];
}
export default usePersistentState;