showing results for - "reading json from localstorage"
Sara
23 Apr 2019
1type Result =
2  | { success: true, value: unknown }
3  | { success: false, error: Error };
4
5function tryDeserializeLocalStorageItem(key: string): Result {
6  const item = localStorage.getItem(key);
7
8  if (item === null) {
9    // The item does not exist, thus return an error result
10    return {
11      success: false,
12      error: new Error(`Item with key "${key}" does not exist`)
13    };
14  }
15
16  let value: unknown;
17
18  try {
19    value = JSON.parse(item);
20  } catch (error) {
21    // The item is not valid JSON, thus return an error result
22    return {
23      success: false,
24      error
25    };
26  }
27
28  // Everything's fine, thus return a success result
29  return {
30    success: true,
31    value
32  };
33}
34