Skip to content

Commit

Permalink
Improve state code
Browse files Browse the repository at this point in the history
  • Loading branch information
kertal committed Oct 12, 2021
1 parent 4a97aec commit a330813
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 34 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ export function DiscoverMainApp(props: DiscoverMainProps) {
services,
history,
savedSearch,
indexPatternList,
});

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ import { getStateDefaults } from '../utils/get_state_defaults';
import { DiscoverServices } from '../../../../build_services';
import { SavedSearch } from '../../../../saved_searches';
import { useSavedSearch as useSavedSearchData } from './use_saved_search';
import { SEARCH_FIELDS_FROM_SOURCE, SEARCH_ON_PAGE_LOAD_SETTING } from '../../../../../common';
import { SEARCH_FIELDS_FROM_SOURCE } from '../../../../../common';
import { useSearchSession } from './use_search_session';
import { FetchStatus } from '../../../types';
import { DiscoverContext } from './discover_context';
import { IndexPattern } from '../../../../../../data_views/common';

export function useDiscoverState({
services,
Expand All @@ -28,23 +28,24 @@ export function useDiscoverState({
history: History;
}) {
const { uiSettings: config, data } = services;
const useNewFieldsApi = useMemo(() => !config.get(SEARCH_FIELDS_FROM_SOURCE), [config]);
const { timefilter } = data.query.timefilter;
const [indexPattern, setIndexPattern] = useState(savedSearch.searchSource.getField('index'));

const {
dataViews: { get },
} = useContext(DiscoverContext);

const useNewFieldsApi = useMemo(() => !config.get(SEARCH_FIELDS_FROM_SOURCE), [config]);
const [indexPattern, setIndexPattern] = useState<IndexPattern | undefined>();
const searchSource = useMemo(() => savedSearch.searchSource.createChild(), [savedSearch]);

const stateContainer = useMemo(() => getState({ history, services }), [services, history]);
const [state, setState] = useState(stateContainer.appStateContainer.getState());

const { appStateContainer } = stateContainer;

/**
* Load index pattern
*/
useEffect(() => {
const load = async () => {
const loadIndexPattern = async () => {
if (!savedSearch?.searchSource.getField('index')) {
const { index, timefield } = appStateContainer.getState();
const loadedIndexPattern = await get(
Expand All @@ -57,30 +58,19 @@ export function useDiscoverState({
setIndexPattern(savedSearch?.searchSource.getField('index'));
}
};
load();
loadIndexPattern();
}, [appStateContainer, get, savedSearch.searchSource, services.uiSettings]);

/**
* Search session logic
*/
const searchSessionManager = useSearchSession({ services, history, stateContainer, savedSearch });

const initialFetchStatus: FetchStatus = useMemo(() => {
// A saved search is created on every page load, so we check the ID to see if we're loading a
// previously saved search or if it is just transient
const shouldSearchOnPageLoad =
config.get<boolean>(SEARCH_ON_PAGE_LOAD_SETTING) ||
savedSearch.id !== undefined ||
timefilter.getRefreshInterval().pause === false ||
searchSessionManager.hasSearchSessionIdInURL();
return shouldSearchOnPageLoad ? FetchStatus.LOADING : FetchStatus.UNINITIALIZED;
}, [config, savedSearch.id, searchSessionManager, timefilter]);

/**
* Data fetching logic
*/
const { data$, refetch$, reset, inspectorAdapters } = useSavedSearchData({
initialFetchStatus,
savedSearch,
searchSessionManager,
searchSource,
services,
Expand All @@ -92,7 +82,7 @@ export function useDiscoverState({
* Start syncing of state to URL of state if searchSource is complete (existing index pattern)
*/
useEffect(() => {
if (savedSearch.searchSource.getField('index')) {
if (indexPattern && savedSearch.searchSource.getField('index') === indexPattern) {
const prevState = stateContainer.appStateContainer.getState();
const stopSync = stateContainer.initializeAndSync(savedSearch);
const nextState = stateContainer.appStateContainer.getState();
Expand Down Expand Up @@ -194,7 +184,7 @@ export function useDiscoverState({
if (indexPattern) {
refetch$.next();
}
}, [initialFetchStatus, refetch$, indexPattern, savedSearch.id]);
}, [refetch$, indexPattern, savedSearch.id]);

return {
data$,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { fetchAll } from '../utils/fetch_all';
import { useBehaviorSubject } from '../utils/use_behavior_subject';
import { sendResetMsg } from './use_saved_search_messages';
import { getFetch$ } from '../utils/get_fetch_observable';
import { SavedSearch } from '../../../../saved_searches';
import { getInitialFetchStatus } from '../utils/get_initial_fetch_status';

export interface SavedSearchData {
main$: DataMain$;
Expand Down Expand Up @@ -82,36 +84,48 @@ export interface DataChartsMessage extends DataMsg {
* to the data fetching
*/
export const useSavedSearch = ({
initialFetchStatus,
searchSessionManager,
savedSearch,
searchSource,
services,
stateContainer,
useNewFieldsApi,
}: {
initialFetchStatus: FetchStatus;
searchSessionManager: DiscoverSearchSessionManager;
savedSearch: SavedSearch;
searchSource: SearchSource;
services: DiscoverServices;
stateContainer: GetStateReturn;
useNewFieldsApi: boolean;
}) => {
const { data, filterManager } = services;
const { data } = services;
const timefilter = data.query.timefilter.timefilter;

const initialFetchStatus: FetchStatus = useMemo(() => {
// A saved search is created on every page load, so we check the ID to see if we're loading a
// previously saved search or if it is just transient
return getInitialFetchStatus(savedSearch, searchSessionManager, services);
}, [savedSearch, searchSessionManager, services]);

const inspectorAdapters = useMemo(() => ({ requests: new RequestAdapter() }), []);

/**
* The observables the UI (aka React component) subscribes to get notified about
* the changes in the data fetching process (high level: fetching started, data was received)
*/
const main$: DataMain$ = useBehaviorSubject({ fetchStatus: initialFetchStatus });
const main$: DataMain$ = useBehaviorSubject({ fetchStatus: initialFetchStatus } as DataMainMsg);

const documents$: DataDocuments$ = useBehaviorSubject({ fetchStatus: initialFetchStatus });
const documents$: DataDocuments$ = useBehaviorSubject({
fetchStatus: initialFetchStatus,
} as DataDocumentsMsg);

const totalHits$: DataTotalHits$ = useBehaviorSubject({ fetchStatus: initialFetchStatus });
const totalHits$: DataTotalHits$ = useBehaviorSubject({
fetchStatus: initialFetchStatus,
} as DataTotalHitsMsg);

const charts$: DataCharts$ = useBehaviorSubject({ fetchStatus: initialFetchStatus });
const charts$: DataCharts$ = useBehaviorSubject({
fetchStatus: initialFetchStatus,
} as DataChartsMessage);

const dataSubjects = useMemo(() => {
return {
Expand Down Expand Up @@ -195,18 +209,14 @@ export const useSavedSearch = ({
return () => subscription.unsubscribe();
}, [
data,
data.query.queryString,
dataSubjects,
filterManager,
initialFetchStatus,
inspectorAdapters,
main$,
refetch$,
searchSessionManager,
searchSessionManager.newSearchSessionIdFromURL$,
searchSource,
services,
services.toastNotifications,
stateContainer.appStateContainer,
timefilter,
useNewFieldsApi,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { SEARCH_ON_PAGE_LOAD_SETTING } from '../../../../../common';
import { FetchStatus } from '../../../types';
import { DiscoverServices } from '../../../../build_services';
import { DiscoverSearchSessionManager } from '../services/discover_search_session';
import { SavedSearch } from '../../../../saved_searches';

export function getInitialFetchStatus(
savedSearch: SavedSearch,
searchSessionManager: DiscoverSearchSessionManager,
services: DiscoverServices
) {
const { timefilter } = services.data.query.timefilter;
const shouldSearchOnPageLoad =
services.uiSettings.get<boolean>(SEARCH_ON_PAGE_LOAD_SETTING) ||
savedSearch.id !== undefined ||
timefilter.getRefreshInterval().pause === false ||
searchSessionManager.hasSearchSessionIdInURL();
return shouldSearchOnPageLoad ? FetchStatus.LOADING : FetchStatus.UNINITIALIZED;
}

0 comments on commit a330813

Please sign in to comment.