import React from 'react'; import {httpRequestJsonLocal} from 'core/helpers/network'; import {noop} from 'lodash'; /** * Wraps a promise in order to ignore AbortError and break the promise chain when it occurs. */ export function ignoreAbortError(promise: Promise): Promise { return new Promise((resolve, reject) => { promise .then(resolve) .catch((err) => { if (err?.name !== 'AbortError') { reject(err); } }); }); } export class SuperdeskReactComponent extends React.PureComponent { public abortController: AbortController; /** * Will automatically abort in-progress asynchronous operations(only those in asyncHelpers) when unmounting. */ public asyncHelpers: { fetch: (input: RequestInfo, init?: RequestInit) => Promise; httpRequestJsonLocal: (options: Parameters[0]) => Promise; }; constructor(props: IProps) { super(props); const abortController = new AbortController(); this.abortController = abortController; this.asyncHelpers = { fetch: (input: RequestInfo, init?: RequestInit): Promise => { return ignoreAbortError( fetch(input, {...(init ?? {}), signal: abortController.signal}), ); }, httpRequestJsonLocal: (options: Parameters[0]) => { return ignoreAbortError( httpRequestJsonLocal({...options, abortSignal: abortController.signal}), ); }, }; // Save before overwriting. const componentWillUnmountChild = this.componentWillUnmount?.bind(this) ?? noop; this.componentWillUnmount = () => { abortController.abort(); componentWillUnmountChild(); }; } }