Skip to content

Instantly share code, notes, and snippets.

@y-nk
Last active May 25, 2021 11:17
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 y-nk/a5ad1d566326bf95944cf15e84b76ac4 to your computer and use it in GitHub Desktop.
Save y-nk/a5ad1d566326bf95944cf15e84b76ac4 to your computer and use it in GitHub Desktop.
// manually generate token for a given page (for when data is available in local)
generateTokenForPage(page: number): string {
return btoa(JSON.stringify({ skip: page * this.recordsPerPage, limit: this.recordsPerPage }));
}
/**
* Reset the current records being contained to the default first page.
*
* @memberof LiveCollection
*/
resetPage() {
this._page = 0;
this._token = undefined;
// even though models.length !== 0 because dataStatus === local !!!
if (this.models.length > 0) {
this._token = this._transaction.generateTokenForPage(1);
}
this._loadData();
}
import { useState, useEffect } from 'react';
//import { LoadingStatus } from '@amityco/js-sdk';
const noop = () => {
if (process?.env?.NODE_ENV === 'development') console.warn('[useLiveCollection] noop hit');
};
const useLiveCollection = (
createLiveCollection,
dependencies = [],
resolver = () => dependencies.some(dep => !dep),
debug = null,
) => {
const [data, setData] = useState({
items: [],
hasMore: false,
loadMore: noop,
});
useEffect(() => {
if (resolver()) return;
const liveCollection = createLiveCollection();
const updateLiveCollection = items => {
setTimeout(() => {
debug && console.log(debug, liveCollection.dataStatus, liveCollection.hasMore);
const { hasMore = false } = liveCollection;
setData({
items,
hasMore,
loadMore: hasMore ? () => liveCollection.nextPage() : noop,
});
}, 0);
};
if (debug) {
window.lc = liveCollection;
}
try {
liveCollection.on('dataUpdated', models => {
debug && console.log('dataUpdated!');
updateLiveCollection(models);
});
if (liveCollection.models) {
debug && console.log('from client cache');
updateLiveCollection(liveCollection.models);
}
} catch (err) {
if (process.env.NODE_ENV === 'development')
console.warn('[useLiveCollection] error thrown', err);
}
return () => liveCollection.dispose();
}, [...dependencies]);
return [data.items, data.hasMore, data.loadMore];
};
export default useLiveCollection;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment