fix: try/catch for invalid values stored in local storage (#301)

This commit is contained in:
Dakshesh Jain 2023-02-17 20:10:02 +05:30 committed by GitHub
parent fcb932dc5d
commit d71cf567e9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,8 +1,13 @@
import { useState, useEffect, useCallback } from "react"; import { useState, useEffect, useCallback } from "react";
const getValueFromLocalStorage = (key: string, defaultValue: any) => { const getValueFromLocalStorage = (key: string, defaultValue: any) => {
const value = window.localStorage.getItem(key); try {
return value ? JSON.parse(value) : defaultValue; const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
} catch (error) {
window.localStorage.removeItem(key);
return defaultValue;
}
}; };
const useLocalStorage = <T,>(key: string, initialValue: T) => { const useLocalStorage = <T,>(key: string, initialValue: T) => {