Skip to content

Commit

Permalink
[Stack Monitoring] Ensure GlobalState class has it's destroy() method…
Browse files Browse the repository at this point in the history
… called on unmount (elastic#139908)

* Ensure GlobalState class has it's destroy() method called

* Move GlobalState instantiation to useState

Co-authored-by: Anton Dosov <[email protected]>
(cherry picked from commit 875a624)
  • Loading branch information
Kerry350 committed Sep 6, 2022
1 parent dd84ba8 commit 278f341
Showing 1 changed file with 11 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -65,5 +68,9 @@ export const GlobalStateProvider: React.FC<GlobalStateProviderProps> = ({
localState.save();
}

useUnmount(() => {
globalState.destroy();
});

return <GlobalStateContext.Provider value={localState}>{children}</GlobalStateContext.Provider>;
};

0 comments on commit 278f341

Please sign in to comment.