Skip to content
This repository has been archived by the owner on Nov 11, 2023. It is now read-only.

Commit

Permalink
Factor out data resolver
Browse files Browse the repository at this point in the history
  • Loading branch information
peterszerzo committed Oct 18, 2018
1 parent cd3e8a2 commit 7e54f91
Showing 1 changed file with 33 additions and 20 deletions.
53 changes: 33 additions & 20 deletions src/Get.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,37 @@ export interface GetState<TData, TError> {
loading: boolean;
}

export const resolveData = async <TData, TError>({
data,
resolve,
}: {
data: any;
resolve?: ResolveFunction<TData>;
}): Promise<{ data: TData | null; error: GetDataError<TError> | null }> => {
let resolvedData: TData | null = null;
let resolveError: GetDataError<TError> | null = null;
try {
if (resolve) {
const resolvedDataOrPromise: TData | Promise<TData> = 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 <Get /> component without Context. This
* is a named class because it is useful in
Expand Down Expand Up @@ -227,27 +258,9 @@ class ContextlessGet<TData, TError> extends React.Component<
return null;
}

let resolvedData: TData | null = null;
let resolveError: GetDataError<TError> | null = null;

try {
if (resolve) {
const resolvedDataOrPromise: TData | Promise<TData> = 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<TData, TError>({ data, resolve });

this.setState({ loading: false, data: resolvedData, error: resolveError });
this.setState({ loading: false, data: resolved.data, error: resolved.error });
return data;
};

Expand Down

0 comments on commit 7e54f91

Please sign in to comment.