"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useFetch = void 0; var _react = require("react"); var _use_track_http_request = require("../../lib/apm/use_track_http_request"); /* * 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; you may not use this file except in compliance with the Elastic License * 2.0. */ const requestReducer = (state, action) => { switch (action.type) { case 'FETCH_INIT': return { ...state, parameters: action.payload, isLoading: true }; case 'FETCH_SUCCESS': return { ...state, data: action.payload, isLoading: false, error: undefined }; case 'FETCH_FAILURE': return { ...state, error: action.payload, isLoading: false }; case 'FETCH_REPEAT': return { ...state, isLoading: true }; default: return state; } }; /** * `useFetch` is a generic hook that simplifies the async request queries implementation. * It provides: APM monitoring, abort control, error handling and refetching. * @param requestName The unique name of the request. It is used for APM tracking, it should be descriptive. * @param fetchFn The function provided to execute the fetch request. It should accept the request `parameters` and the abort `signal`. * @param options Additional options. */ const useFetch = (requestName, fetchFn, { disabled = false, initialParameters } = {}) => { const { startTracking } = (0, _use_track_http_request.useTrackHttpRequest)(); const [{ parameters, data, isLoading, error }, dispatch] = (0, _react.useReducer)(requestReducer, { data: undefined, isLoading: !disabled && initialParameters !== undefined, // isLoading state is used internally to control fetch executions error: undefined, parameters: initialParameters }); const fetch = (0, _react.useCallback)(param => dispatch({ type: 'FETCH_INIT', payload: param }), []); const refetch = (0, _react.useCallback)(() => dispatch({ type: 'FETCH_REPEAT' }), []); (0, _react.useEffect)(() => { if (isLoading === false || parameters === undefined || disabled) { return; } let ignore = false; const abortController = new AbortController(); const executeFetch = async () => { const { endTracking } = startTracking({ name: requestName }); try { const response = await fetchFn(parameters, abortController.signal); endTracking('success'); if (!ignore) { dispatch({ type: 'FETCH_SUCCESS', payload: response }); } } catch (err) { endTracking(abortController.signal.aborted ? 'aborted' : 'error'); if (!ignore) { dispatch({ type: 'FETCH_FAILURE', payload: err }); } } }; executeFetch(); return () => { ignore = true; abortController.abort(); }; }, [isLoading, parameters, disabled, fetchFn, startTracking, requestName]); return { fetch, refetch, data, isLoading, error }; }; exports.useFetch = useFetch;