Skip to content

Commit

Permalink
Rename useRequest's sendRequest return function to resendRequest and …
Browse files Browse the repository at this point in the history
…remove return value (#76795)
  • Loading branch information
cjcenizal authored Sep 10, 2020
1 parent ae9a9c2 commit e2cbd89
Show file tree
Hide file tree
Showing 36 changed files with 96 additions and 95 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export const createUseRequestHelpers = (): UseRequestHelpers => {
};

const TestComponent = ({ requestConfig }: { requestConfig: UseRequestConfig }) => {
const { isInitialRequest, isLoading, error, data, sendRequest } = useRequest(
const { isInitialRequest, isLoading, error, data, resendRequest } = useRequest(
httpClient as HttpSetup,
requestConfig
);
Expand All @@ -115,7 +115,7 @@ export const createUseRequestHelpers = (): UseRequestHelpers => {
hookResult.isLoading = isLoading;
hookResult.error = error;
hookResult.data = data;
hookResult.sendRequest = sendRequest;
hookResult.resendRequest = resendRequest;

return null;
};
Expand Down
22 changes: 11 additions & 11 deletions src/plugins/es_ui_shared/public/request/use_request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ describe('useRequest hook', () => {
setupSuccessRequest();
expect(hookResult.isInitialRequest).toBe(true);

hookResult.sendRequest();
hookResult.resendRequest();
await completeRequest();
expect(hookResult.isInitialRequest).toBe(false);
});
Expand Down Expand Up @@ -148,7 +148,7 @@ describe('useRequest hook', () => {
expect(hookResult.error).toBe(getErrorResponse().error);

act(() => {
hookResult.sendRequest();
hookResult.resendRequest();
});
expect(hookResult.isLoading).toBe(true);
expect(hookResult.error).toBe(getErrorResponse().error);
Expand Down Expand Up @@ -183,7 +183,7 @@ describe('useRequest hook', () => {
expect(hookResult.data).toBe(getSuccessResponse().data);

act(() => {
hookResult.sendRequest();
hookResult.resendRequest();
});
expect(hookResult.isLoading).toBe(true);
expect(hookResult.data).toBe(getSuccessResponse().data);
Expand Down Expand Up @@ -215,7 +215,7 @@ describe('useRequest hook', () => {
});

describe('callbacks', () => {
describe('sendRequest', () => {
describe('resendRequest', () => {
it('sends the request', async () => {
const { setupSuccessRequest, completeRequest, hookResult, getSendRequestSpy } = helpers;
setupSuccessRequest();
Expand All @@ -224,7 +224,7 @@ describe('useRequest hook', () => {
expect(getSendRequestSpy().callCount).toBe(1);

await act(async () => {
hookResult.sendRequest();
hookResult.resendRequest();
await completeRequest();
});
expect(getSendRequestSpy().callCount).toBe(2);
Expand All @@ -239,17 +239,17 @@ describe('useRequest hook', () => {
await advanceTime(REQUEST_TIME);
expect(getSendRequestSpy().callCount).toBe(1);
act(() => {
hookResult.sendRequest();
hookResult.resendRequest();
});

// The manual request resolves, and we'll send yet another one...
await advanceTime(REQUEST_TIME);
expect(getSendRequestSpy().callCount).toBe(2);
act(() => {
hookResult.sendRequest();
hookResult.resendRequest();
});

// At this point, we've moved forward 3s. The poll is set at 2s. If sendRequest didn't
// At this point, we've moved forward 3s. The poll is set at 2s. If resendRequest didn't
// reset the poll, the request call count would be 4, not 3.
await advanceTime(REQUEST_TIME);
expect(getSendRequestSpy().callCount).toBe(3);
Expand Down Expand Up @@ -291,14 +291,14 @@ describe('useRequest hook', () => {
const HALF_REQUEST_TIME = REQUEST_TIME * 0.5;
setupSuccessRequest({ pollIntervalMs: REQUEST_TIME });

// Before the original request resolves, we make a manual sendRequest call.
// Before the original request resolves, we make a manual resendRequest call.
await advanceTime(HALF_REQUEST_TIME);
expect(getSendRequestSpy().callCount).toBe(0);
act(() => {
hookResult.sendRequest();
hookResult.resendRequest();
});

// The original quest resolves but it's been marked as outdated by the the manual sendRequest
// The original quest resolves but it's been marked as outdated by the the manual resendRequest
// call "interrupts", so data is left undefined.
await advanceTime(HALF_REQUEST_TIME);
expect(getSendRequestSpy().callCount).toBe(1);
Expand Down
30 changes: 12 additions & 18 deletions src/plugins/es_ui_shared/public/request/use_request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,7 @@
import { useEffect, useCallback, useState, useRef, useMemo } from 'react';

import { HttpSetup } from '../../../../../src/core/public';
import {
sendRequest as sendStatelessRequest,
SendRequestConfig,
SendRequestResponse,
} from './send_request';
import { sendRequest, SendRequestConfig } from './send_request';

export interface UseRequestConfig extends SendRequestConfig {
pollIntervalMs?: number;
Expand All @@ -37,7 +33,7 @@ export interface UseRequestResponse<D = any, E = Error> {
isLoading: boolean;
error: E | null;
data?: D | null;
sendRequest: () => Promise<SendRequestResponse<D, E>>;
resendRequest: () => void;
}

export const useRequest = <D = any, E = Error>(
Expand Down Expand Up @@ -80,7 +76,7 @@ export const useRequest = <D = any, E = Error>(
/* eslint-disable-next-line react-hooks/exhaustive-deps */
}, [path, method, queryStringified, bodyStringified]);

const sendRequest = useCallback(async () => {
const resendRequest = useCallback(async () => {
// If we're on an interval, this allows us to reset it if the user has manually requested the
// data, to avoid doubled-up requests.
clearPollInterval();
Expand All @@ -91,15 +87,15 @@ export const useRequest = <D = any, E = Error>(
// "old" error/data or loading state when a new request is in-flight.
setIsLoading(true);

const response = await sendStatelessRequest<D, E>(httpClient, requestBody);
const response = await sendRequest<D, E>(httpClient, requestBody);
const { data: serializedResponseData, error: responseError } = response;

const isOutdatedRequest = requestId !== requestCountRef.current;
const isUnmounted = isMounted.current === false;

// Ignore outdated or irrelevant data.
if (isOutdatedRequest || isUnmounted) {
return { data: null, error: null };
return;
}

setError(responseError);
Expand All @@ -112,28 +108,26 @@ export const useRequest = <D = any, E = Error>(
}
// Setting isLoading to false also acts as a signal for scheduling the next poll request.
setIsLoading(false);

return { data: serializedResponseData, error: responseError };
}, [requestBody, httpClient, deserializer, clearPollInterval]);

const scheduleRequest = useCallback(() => {
// If there's a scheduled poll request, this new one will supersede it.
clearPollInterval();

if (pollIntervalMs) {
pollIntervalIdRef.current = setTimeout(sendRequest, pollIntervalMs);
pollIntervalIdRef.current = setTimeout(resendRequest, pollIntervalMs);
}
}, [pollIntervalMs, sendRequest, clearPollInterval]);
}, [pollIntervalMs, resendRequest, clearPollInterval]);

// Send the request on component mount and whenever the dependencies of sendRequest() change.
// Send the request on component mount and whenever the dependencies of resendRequest() change.
useEffect(() => {
sendRequest();
}, [sendRequest]);
resendRequest();
}, [resendRequest]);

// Schedule the next poll request when the previous one completes.
useEffect(() => {
// When a request completes, attempt to schedule the next one. Note that we aren't re-scheduling
// a request whenever sendRequest's dependencies change. isLoading isn't set to false until the
// a request whenever resendRequest's dependencies change. isLoading isn't set to false until the
// initial request has completed, so we won't schedule a request on mount.
if (!isLoading) {
scheduleRequest();
Expand All @@ -156,6 +150,6 @@ export const useRequest = <D = any, E = Error>(
isLoading,
error,
data,
sendRequest, // Gives the user the ability to manually request data
resendRequest, // Gives the user the ability to manually request data
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const NodeAllocation = <T extends PhaseWithAllocationAction>({
phaseData,
isShowingErrors,
}: React.PropsWithChildren<Props<T>>) => {
const { isLoading, data: nodes, error, sendRequest } = useLoadNodes();
const { isLoading, data: nodes, error, resendRequest } = useLoadNodes();

const [selectedNodeAttrsForDetails, setSelectedNodeAttrsForDetails] = useState<string | null>(
null
Expand Down Expand Up @@ -84,7 +84,7 @@ export const NodeAllocation = <T extends PhaseWithAllocationAction>({
<p>
{message} ({statusCode})
</p>
<EuiButton onClick={sendRequest} iconType="refresh" color="danger">
<EuiButton onClick={resendRequest} iconType="refresh" color="danger">
<FormattedMessage
id="xpack.indexLifecycleMgmt.editPolicy.nodeAttributesReloadButton"
defaultMessage="Try again"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ interface Props {
}

export const NodeAttrsDetails: React.FunctionComponent<Props> = ({ close, selectedNodeAttrs }) => {
const { data, isLoading, error, sendRequest } = useLoadNodeDetails(selectedNodeAttrs);
const { data, isLoading, error, resendRequest } = useLoadNodeDetails(selectedNodeAttrs);
let content;
if (isLoading) {
content = <EuiLoadingContent lines={3} />;
Expand All @@ -47,7 +47,7 @@ export const NodeAttrsDetails: React.FunctionComponent<Props> = ({ close, select
<p>
{message} ({statusCode})
</p>
<EuiButton onClick={sendRequest} iconType="refresh" color="danger">
<EuiButton onClick={resendRequest} iconType="refresh" color="danger">
<FormattedMessage
id="xpack.indexLifecycleMgmt.editPolicy.nodeDetailsReloadButton"
defaultMessage="Try again"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const SnapshotPolicies: React.FunctionComponent<Props> = ({
onChange,
getUrlForApp,
}) => {
const { error, isLoading, data, sendRequest } = useLoadSnapshotPolicies();
const { error, isLoading, data, resendRequest } = useLoadSnapshotPolicies();

const policies = data.map((name: string) => ({
label: name,
Expand Down Expand Up @@ -75,7 +75,7 @@ export const SnapshotPolicies: React.FunctionComponent<Props> = ({
<EuiButtonIcon
size="s"
color="warning"
onClick={sendRequest}
onClick={resendRequest}
iconType="refresh"
aria-label={i18n.translate(
'xpack.indexLifecycleMgmt.editPolicy.deletePhase.reloadPoliciesLabel',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const EditPolicy: React.FunctionComponent<Props & RouteComponentProps<Rou
getUrlForApp,
history,
}) => {
const { error, isLoading, data: policies, sendRequest } = useLoadPoliciesList(false);
const { error, isLoading, data: policies, resendRequest } = useLoadPoliciesList(false);
if (isLoading) {
return (
<EuiEmptyPrompt
Expand Down Expand Up @@ -65,7 +65,7 @@ export const EditPolicy: React.FunctionComponent<Props & RouteComponentProps<Rou
</p>
}
actions={
<EuiButton onClick={sendRequest} iconType="refresh" color="danger">
<EuiButton onClick={resendRequest} iconType="refresh" color="danger">
<FormattedMessage
id="xpack.indexLifecycleMgmt.editPolicy.lifecyclePoliciesReloadButton"
defaultMessage="Try again"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const PolicyTable: React.FunctionComponent<Props & RouteComponentProps> =
navigateToApp,
history,
}) => {
const { data: policies, isLoading, error, sendRequest } = useLoadPoliciesList(true);
const { data: policies, isLoading, error, resendRequest } = useLoadPoliciesList(true);

if (isLoading) {
return (
Expand Down Expand Up @@ -53,7 +53,7 @@ export const PolicyTable: React.FunctionComponent<Props & RouteComponentProps> =
</p>
}
actions={
<EuiButton onClick={sendRequest} iconType="refresh" color="danger">
<EuiButton onClick={resendRequest} iconType="refresh" color="danger">
<FormattedMessage
id="xpack.indexLifecycleMgmt.policyTable.policiesReloadButton"
defaultMessage="Try again"
Expand All @@ -69,7 +69,7 @@ export const PolicyTable: React.FunctionComponent<Props & RouteComponentProps> =
policies={policies || []}
history={history}
navigateToApp={navigateToApp}
updatePolicies={sendRequest}
updatePolicies={resendRequest}
/>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const ComponentTemplateList: React.FunctionComponent<Props> = ({
} = useGlobalFlyout();
const { api, trackMetric, documentation } = useComponentTemplatesContext();

const { data, isLoading, error, sendRequest } = api.useLoadComponentTemplates();
const { data, isLoading, error, resendRequest } = api.useLoadComponentTemplates();

const [componentTemplatesToDelete, setComponentTemplatesToDelete] = useState<string[]>([]);

Expand Down Expand Up @@ -170,7 +170,7 @@ export const ComponentTemplateList: React.FunctionComponent<Props> = ({

<ComponentTable
componentTemplates={data}
onReloadClick={sendRequest}
onReloadClick={resendRequest}
onDeleteClick={setComponentTemplatesToDelete}
onEditClick={goToEditComponentTemplate}
onCloneClick={goToCloneComponentTemplate}
Expand All @@ -181,7 +181,7 @@ export const ComponentTemplateList: React.FunctionComponent<Props> = ({
} else if (data && data.length === 0) {
content = <EmptyPrompt history={history} />;
} else if (error) {
content = <LoadError onReloadClick={sendRequest} />;
content = <LoadError onReloadClick={resendRequest} />;
}

return (
Expand All @@ -194,7 +194,7 @@ export const ComponentTemplateList: React.FunctionComponent<Props> = ({
callback={(deleteResponse) => {
if (deleteResponse?.hasDeletedComponentTemplates) {
// refetch the component templates
sendRequest();
resendRequest();
// go back to list view (if deleted from details flyout)
goToComponentTemplateList();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const DataStreamList: React.FunctionComponent<RouteComponentProps<MatchPa
} = useAppContext();

const [isIncludeStatsChecked, setIsIncludeStatsChecked] = useState(false);
const { error, isLoading, data: dataStreams, sendRequest: reload } = useLoadDataStreams({
const { error, isLoading, data: dataStreams, resendRequest: reload } = useLoadDataStreams({
includeStats: isIncludeStatsChecked,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { EuiInMemoryTable, EuiBasicTableColumn, EuiButton, EuiLink } from '@elas
import { ScopedHistory } from 'kibana/public';

import { DataStream } from '../../../../../../common/types';
import { reactRouterNavigate } from '../../../../../shared_imports';
import { UseRequestResponse, reactRouterNavigate } from '../../../../../shared_imports';
import { encodePathForReactRouter } from '../../../../services/routing';
import { DataHealth } from '../../../../components';
import { Section } from '../../../home';
Expand All @@ -20,7 +20,7 @@ import { humanizeTimeStamp } from '../humanize_time_stamp';

interface Props {
dataStreams?: DataStream[];
reload: () => {};
reload: UseRequestResponse['resendRequest'];
history: ScopedHistory;
includeStats: boolean;
filters?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
import { EuiInMemoryTable, EuiButton, EuiLink, EuiBasicTableColumn } from '@elastic/eui';
import { ScopedHistory } from 'kibana/public';
import { SendRequestResponse, reactRouterNavigate } from '../../../../../../shared_imports';
import { UseRequestResponse, reactRouterNavigate } from '../../../../../../shared_imports';
import { TemplateListItem } from '../../../../../../../common';
import { UIM_TEMPLATE_SHOW_DETAILS_CLICK } from '../../../../../../../common/constants';
import { TemplateDeleteModal } from '../../../../../components';
Expand All @@ -20,7 +20,7 @@ import { TemplateTypeIndicator } from '../../components';

interface Props {
templates: TemplateListItem[];
reload: () => Promise<SendRequestResponse>;
reload: UseRequestResponse['resendRequest'];
editTemplate: (name: string, isLegacy?: boolean) => void;
cloneTemplate: (name: string, isLegacy?: boolean) => void;
history: ScopedHistory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
UIM_TEMPLATE_DETAIL_PANEL_ALIASES_TAB,
UIM_TEMPLATE_DETAIL_PANEL_PREVIEW_TAB,
} from '../../../../../../common/constants';
import { SendRequestResponse } from '../../../../../shared_imports';
import { UseRequestResponse } from '../../../../../shared_imports';
import { TemplateDeleteModal, SectionLoading, SectionError, Error } from '../../../../components';
import { useLoadIndexTemplate } from '../../../../services/api';
import { decodePathFromReactRouter } from '../../../../services/routing';
Expand Down Expand Up @@ -92,7 +92,7 @@ export interface Props {
onClose: () => void;
editTemplate: (name: string, isLegacy?: boolean) => void;
cloneTemplate: (name: string, isLegacy?: boolean) => void;
reload: () => Promise<SendRequestResponse>;
reload: UseRequestResponse['resendRequest'];
}

export const TemplateDetailsContent = ({
Expand Down
Loading

0 comments on commit e2cbd89

Please sign in to comment.