Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[7.12] [APM] Fix for default fields in correlations view (#91868) (#92090) #92951

Merged
merged 2 commits into from
Mar 1, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 22 additions & 20 deletions x-pack/plugins/apm/public/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,10 @@
import { useState, useEffect } from 'react';

export function useLocalStorage<T>(key: string, defaultValue: T) {
const [item, setItem] = useState<T>(getFromStorage());

function getFromStorage() {
const storedItem = window.localStorage.getItem(key);

let toStore: T = defaultValue;

if (storedItem !== null) {
try {
toStore = JSON.parse(storedItem) as T;
} catch (err) {
window.localStorage.removeItem(key);
// eslint-disable-next-line no-console
console.log(`Unable to decode: ${key}`);
}
}

return toStore;
}
const [item, setItem] = useState<T>(getFromStorage(key, defaultValue));

const updateFromStorage = () => {
const storedItem = getFromStorage();
const storedItem = getFromStorage(key, defaultValue);
setItem(storedItem);
};

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

// item state must be updated with a new key or default value
useEffect(() => {
setItem(getFromStorage(key, defaultValue));
}, [key, defaultValue]);

return [item, saveToStorage] as const;
}

function getFromStorage<T>(keyName: string, defaultValue: T) {
const storedItem = window.localStorage.getItem(keyName);

if (storedItem !== null) {
try {
return JSON.parse(storedItem) as T;
} catch (err) {
window.localStorage.removeItem(keyName);
// eslint-disable-next-line no-console
console.log(`Unable to decode: ${keyName}`);
}
}
return defaultValue;
}