Created
January 20, 2019 14:10
-
-
Save DarkoKukovec/8436bb1349ecf5a8e99bfcd0925d69d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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