Skip to content

Commit d5e8c0f

Browse files
[APM] Fix for default fields in correlations view (#91868) (#92090) (#92950)
* [APM] Fix for default fields in correlations view (#91868) * removes useCallback hook Co-authored-by: Kibana Machine <[email protected]> Co-authored-by: Kibana Machine <[email protected]>
1 parent f61d1d3 commit d5e8c0f

File tree

1 file changed

+22
-20
lines changed

1 file changed

+22
-20
lines changed

x-pack/plugins/apm/public/hooks/useLocalStorage.ts

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,28 +8,10 @@
88
import { useState, useEffect } from 'react';
99

1010
export function useLocalStorage<T>(key: string, defaultValue: T) {
11-
const [item, setItem] = useState<T>(getFromStorage());
12-
13-
function getFromStorage() {
14-
const storedItem = window.localStorage.getItem(key);
15-
16-
let toStore: T = defaultValue;
17-
18-
if (storedItem !== null) {
19-
try {
20-
toStore = JSON.parse(storedItem) as T;
21-
} catch (err) {
22-
window.localStorage.removeItem(key);
23-
// eslint-disable-next-line no-console
24-
console.log(`Unable to decode: ${key}`);
25-
}
26-
}
27-
28-
return toStore;
29-
}
11+
const [item, setItem] = useState<T>(getFromStorage(key, defaultValue));
3012

3113
const updateFromStorage = () => {
32-
const storedItem = getFromStorage();
14+
const storedItem = getFromStorage(key, defaultValue);
3315
setItem(storedItem);
3416
};
3517

@@ -51,5 +33,25 @@ export function useLocalStorage<T>(key: string, defaultValue: T) {
5133
// eslint-disable-next-line react-hooks/exhaustive-deps
5234
}, []);
5335

36+
// item state must be updated with a new key or default value
37+
useEffect(() => {
38+
setItem(getFromStorage(key, defaultValue));
39+
}, [key, defaultValue]);
40+
5441
return [item, saveToStorage] as const;
5542
}
43+
44+
function getFromStorage<T>(keyName: string, defaultValue: T) {
45+
const storedItem = window.localStorage.getItem(keyName);
46+
47+
if (storedItem !== null) {
48+
try {
49+
return JSON.parse(storedItem) as T;
50+
} catch (err) {
51+
window.localStorage.removeItem(keyName);
52+
// eslint-disable-next-line no-console
53+
console.log(`Unable to decode: ${keyName}`);
54+
}
55+
}
56+
return defaultValue;
57+
}

0 commit comments

Comments
 (0)