Move creation of state container to render-time in order to initialize state from URL correctly (#87955)

This commit is contained in:
Jen Huang 2021-01-12 09:15:07 -08:00 committed by GitHub
parent 2d7a3cedef
commit 44ccf285e5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 25 deletions

View file

@ -36,6 +36,7 @@ export const DEFAULT_LOGS_STATE: AgentLogsState = {
query: '',
};
export const STATE_STORAGE_KEY = '_q';
export const STATE_DATASET_FIELD = 'datasets';
export const AGENT_LOG_LEVELS = {

View file

@ -3,7 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import React, { memo, useEffect, useState } from 'react';
import React, { memo, useEffect, useState, useMemo } from 'react';
import {
createStateContainer,
syncState,
@ -12,38 +12,44 @@ import {
PureTransition,
getStateFromKbnUrl,
} from '../../../../../../../../../../../src/plugins/kibana_utils/public';
import { DEFAULT_LOGS_STATE } from './constants';
import { DEFAULT_LOGS_STATE, STATE_STORAGE_KEY } from './constants';
import { AgentLogsUI, AgentLogsProps, AgentLogsState, AgentLogsUrlStateHelper } from './agent_logs';
const stateStorageKey = '_q';
const stateContainer = createStateContainer<
AgentLogsState,
{
update: PureTransition<AgentLogsState, [Partial<AgentLogsState>]>;
}
>(
{
...DEFAULT_LOGS_STATE,
...getStateFromKbnUrl<AgentLogsState>(stateStorageKey, window.location.href),
},
{
update: (state) => (updatedState) => ({ ...state, ...updatedState }),
}
);
const AgentLogsConnected = AgentLogsUrlStateHelper.connect<AgentLogsProps, 'state'>((state) => ({
state: state || DEFAULT_LOGS_STATE,
}))(AgentLogsUI);
export const AgentLogs: React.FunctionComponent<Pick<AgentLogsProps, 'agent'>> = memo(
({ agent }) => {
const stateContainer = useMemo(
() =>
createStateContainer<
AgentLogsState,
{
update: PureTransition<AgentLogsState, [Partial<AgentLogsState>]>;
}
>(
{
...DEFAULT_LOGS_STATE,
...getStateFromKbnUrl<AgentLogsState>(STATE_STORAGE_KEY, window.location.href),
},
{
update: (state) => (updatedState) => ({ ...state, ...updatedState }),
}
),
[]
);
const AgentLogsConnected = useMemo(
() =>
AgentLogsUrlStateHelper.connect<AgentLogsProps, 'state'>((state) => ({
state: state || DEFAULT_LOGS_STATE,
}))(AgentLogsUI),
[]
);
const [isSyncReady, setIsSyncReady] = useState<boolean>(false);
useEffect(() => {
const stateStorage = createKbnUrlStateStorage();
const { start, stop } = syncState({
storageKey: stateStorageKey,
storageKey: STATE_STORAGE_KEY,
stateContainer: stateContainer as INullableBaseStateContainer<AgentLogsState>,
stateStorage,
});
@ -54,7 +60,7 @@ export const AgentLogs: React.FunctionComponent<Pick<AgentLogsProps, 'agent'>> =
stop();
stateContainer.set(DEFAULT_LOGS_STATE);
};
}, []);
}, [stateContainer]);
return (
<AgentLogsUrlStateHelper.Provider value={stateContainer}>