diff --git a/src/Get.tsx b/src/Get.tsx index f03c025a..212c9ae7 100644 --- a/src/Get.tsx +++ b/src/Get.tsx @@ -118,6 +118,37 @@ export interface GetState { loading: boolean; } +export const resolveData = async ({ + data, + resolve, +}: { + data: any; + resolve?: ResolveFunction; +}): Promise<{ data: TData | null; error: GetDataError | null }> => { + let resolvedData: TData | null = null; + let resolveError: GetDataError | null = null; + try { + if (resolve) { + const resolvedDataOrPromise: TData | Promise = resolve(data); + resolvedData = (resolvedDataOrPromise as { then?: any }).then + ? ((await resolvedDataOrPromise) as TData) + : (resolvedDataOrPromise as TData); + } else { + resolvedData = data; + } + } catch (err) { + resolvedData = null; + resolveError = { + message: "RESOLVE_ERROR", + data: JSON.stringify(err), + }; + } + return { + data: resolvedData, + error: resolveError, + }; +}; + /** * The component without Context. This * is a named class because it is useful in @@ -227,27 +258,9 @@ class ContextlessGet extends React.Component< return null; } - let resolvedData: TData | null = null; - let resolveError: GetDataError | null = null; - - try { - if (resolve) { - const resolvedDataOrPromise: TData | Promise = resolve(data); - resolvedData = (resolvedDataOrPromise as { then?: any }).then - ? ((await resolvedDataOrPromise) as TData) - : (resolvedDataOrPromise as TData); - } else { - resolvedData = data; - } - } catch (err) { - resolvedData = null; - resolveError = { - message: "RESOLVE_ERROR", - data: JSON.stringify(err), - }; - } + const resolved = await resolveData({ data, resolve }); - this.setState({ loading: false, data: resolvedData, error: resolveError }); + this.setState({ loading: false, data: resolved.data, error: resolved.error }); return data; };