Created
January 20, 2019 14:10
-
-
Save DarkoKukovec/38c6a664a324c6ea0509f188af6c3749 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 { 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