From 875a624179a1191f4219da11aa9740b2f6c15f8b Mon Sep 17 00:00:00 2001 From: Kerry Gallagher Date: Tue, 6 Sep 2022 21:32:47 +0100 Subject: [PATCH] [Stack Monitoring] Ensure GlobalState class has it's destroy() method called on unmount (#139908) * Ensure GlobalState class has it's destroy() method called * Move GlobalState instantiation to useState Co-authored-by: Anton Dosov --- .../application/contexts/global_state_context.tsx | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/monitoring/public/application/contexts/global_state_context.tsx b/x-pack/plugins/monitoring/public/application/contexts/global_state_context.tsx index 71180f2c2c92d..7d5ab0be65033 100644 --- a/x-pack/plugins/monitoring/public/application/contexts/global_state_context.tsx +++ b/x-pack/plugins/monitoring/public/application/contexts/global_state_context.tsx @@ -4,9 +4,10 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import React, { createContext } from 'react'; +import React, { createContext, useState } from 'react'; import type { TimeRange } from '@kbn/es-query'; import { RefreshInterval } from '@kbn/data-plugin/public'; +import useUnmount from 'react-use/lib/useUnmount'; import { GlobalState } from '../../url_state'; import { MonitoringStartPluginDependencies, MonitoringStartServices } from '../../types'; import { Legacy } from '../../legacy_shims'; @@ -42,9 +43,11 @@ export const GlobalStateProvider: React.FC = ({ children, }) => { const localState: State = {}; - const state = new GlobalState(query, toasts, localState as { [key: string]: unknown }); + const [globalState] = useState( + () => new GlobalState(query, toasts, localState as { [key: string]: unknown }) + ); - const initialState: any = state.getState(); + const initialState: any = globalState.getState(); for (const key in initialState) { if (!initialState.hasOwnProperty(key)) { continue; @@ -55,7 +58,7 @@ export const GlobalStateProvider: React.FC = ({ localState.save = () => { const newState = { ...localState }; delete newState.save; - state.setState(newState); + globalState.setState(newState); }; // default to an active refresh interval if it's not conflicting with user-defined values @@ -65,5 +68,9 @@ export const GlobalStateProvider: React.FC = ({ localState.save(); } + useUnmount(() => { + globalState.destroy(); + }); + return {children}; };