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/38c6a664a324c6ea0509f188af6c3749 to your computer and use it in GitHub Desktop.
Save DarkoKukovec/38c6a664a324c6ea0509f188af6c3749 to your computer and use it in GitHub Desktop.
import { IJsonapiModel, IJsonapiView, Response } from 'datx-jsonapi';
import { useEffect, useMemo, useState } from 'react';
interface IResponseWithNext<T extends IJsonapiModel> extends Response<T> {
next: Promise<Response<T>>;
}
function responseHasNext(response: IResponseWithNext<IJsonapiModel>): true;
function responseHasNext(response?: Response<IJsonapiModel>): false;
function responseHasNext(response?: Response<IJsonapiModel> | IResponseWithNext<IJsonapiModel>): boolean {
return Boolean(
response &&
response.pageInfo &&
typeof response.pageInfo.currentPage === 'number' &&
typeof response.pageInfo.totalPages === 'number' &&
response.pageInfo.currentPage < response.pageInfo.totalPages &&
'next' in response,
);
}
export const useInfiniteScroll = (view?: IJsonapiView) => {
const [state, setState] = useState({
latestResponse: view ? view.latestResponse : undefined,
loading: false,
view,
});
if (view && view !== state.view) {
setState((oldState) => ({ ...oldState, view }));
}
if (view && view.latestResponse !== state.latestResponse) {
setState((oldState) => ({ ...oldState, latestResponse: view.latestResponse }));
}
const loadMore = () => {
if (state.view && responseHasNext(state.view.latestResponse) && !state.loading) {
setState((oldState) => ({ ...oldState, loading: true }));
(state.view.latestResponse as IResponseWithNext<IJsonapiModel>).next
.then(() => {
setState((oldState) => ({ ...oldState, loading: false }));
}, () => {
setState((oldState) => ({ ...oldState, loading: false }));
});
}
};
return useMemo(() => ({
hasMore: state.latestResponse ? responseHasNext(state.latestResponse) : false,
loadMore,
loading: state.loading,
}), [state]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment