Skip to content

Instantly share code, notes, and snippets.

@DarkoKukovec
Created January 20, 2019 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarkoKukovec/8436bb1349ecf5a8e99bfcd0925d69d7 to your computer and use it in GitHub Desktop.
Save DarkoKukovec/8436bb1349ecf5a8e99bfcd0925d69d7 to your computer and use it in GitHub Desktop.
import { Collection, IModelConstructor, View } from 'datx';
import { IJsonapiModel, IJsonapiView, IRequestOptions, jsonapi } from 'datx-jsonapi';
import { useEffect, useMemo, useState } from 'react';
const JsonapiView = jsonapi(View);
export const useFetchAll = <T extends IJsonapiModel>(
collection: Collection,
model: IModelConstructor<T>,
options?: IRequestOptions,
): {
view?: View<T> & IJsonapiView;
error?: any;
isLoading: boolean;
startedAt?: Date;
finishedAt?: Date;
} => {
const [state, setState] = useState<{
error?: any;
view?: View<T> & IJsonapiView;
startedAt?: Date;
finishedAt?: Date;
}>({});
if (!state.view) {
const view = new JsonapiView(model, collection) as View<T> & IJsonapiView;
setState((oldState) => ({ ...oldState, view }));
}
const load = () => {
if (state.view && !state.startedAt) {
setState((oldState) => ({ ...oldState, startedAt: new Date() }));
state.view.fetchAll(options).then((response) => {
setState((oldState) => ({
...oldState,
error: response.error,
finishedAt: new Date(),
}));
});
}
};
useEffect(load, []);
return useMemo(() => ({
...state,
isLoading: Boolean(state.startedAt) && !Boolean(state.finishedAt),
}), [state]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment