[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 <dosantappdev@gmail.com>
This commit is contained in:
Kerry Gallagher 2022-09-06 21:32:47 +01:00 committed by GitHub
parent c2fbe4710f
commit 875a624179
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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<GlobalStateProviderProps> = ({
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<GlobalStateProviderProps> = ({
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<GlobalStateProviderProps> = ({
localState.save();
}
useUnmount(() => {
globalState.destroy();
});
return <GlobalStateContext.Provider value={localState}>{children}</GlobalStateContext.Provider>;
};