From c00cb8c8968afa635dc124a313a82637fe81a114 Mon Sep 17 00:00:00 2001 From: Oliver Gupte Date: Fri, 19 Feb 2021 16:23:42 -0500 Subject: [PATCH] [APM] Fix for default fields in correlations view (#91868) --- x-pack/plugins/apm/public/hooks/useLocalStorage.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/x-pack/plugins/apm/public/hooks/useLocalStorage.ts b/x-pack/plugins/apm/public/hooks/useLocalStorage.ts index dc07b89ec78076..bf66d364dbcc6f 100644 --- a/x-pack/plugins/apm/public/hooks/useLocalStorage.ts +++ b/x-pack/plugins/apm/public/hooks/useLocalStorage.ts @@ -5,12 +5,10 @@ * 2.0. */ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useCallback } from 'react'; export function useLocalStorage(key: string, defaultValue: T) { - const [item, setItem] = useState(getFromStorage()); - - function getFromStorage() { + const getFromStorage = useCallback(() => { const storedItem = window.localStorage.getItem(key); let toStore: T = defaultValue; @@ -26,7 +24,9 @@ export function useLocalStorage(key: string, defaultValue: T) { } return toStore; - } + }, [key, defaultValue]); + + const [item, setItem] = useState(getFromStorage()); const updateFromStorage = () => { const storedItem = getFromStorage(); @@ -51,5 +51,9 @@ export function useLocalStorage(key: string, defaultValue: T) { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + useEffect(() => { + setItem(getFromStorage()); + }, [getFromStorage]); + return [item, saveToStorage] as const; }