Skip to content

Instantly share code, notes, and snippets.

@philipimperato
Last active February 4, 2023 18:03
Show Gist options
  • Save philipimperato/1135e4ddc6533dfab5ff80f157c2a7db to your computer and use it in GitHub Desktop.
Save philipimperato/1135e4ddc6533dfab5ff80f157c2a7db to your computer and use it in GitHub Desktop.
Simple `useFind` that will preload data, allow for loading more & reseting
import { Ref, ComputedRef } from 'vue'
interface ICommentFindOptions {
increment: number,
initialSize?: number
}
interface ICommentFindResult {
data: ComputedRef<Comment[]>
hasMoreComments: ComputedRef<boolean>
haveLoaded: Ref<boolean>
initial: () => void
loadMore: () => void,
reset: () => void
}
export const useCommentFind = (params: ComputedRef<any>, options: ICommentFindOptions) : ICommentFindResult => {
const haveLoaded = ref(false)
const {
increment,
initialSize = 100
} = options
const commentStore = useCommentStore()
const {
data,
total,
limit,
toPage,
find
} = commentStore.useFind(params)
const initial = async () => {
await find({ query: {}, $skip: 0, $limit: initialSize })
haveLoaded.value = true
}
const loadMore = async () => {
limit.value += increment
if (limit.value >= initialSize) {
const preloadAmt = initialSize + limit.value
await find({ query: {}, $skip: 0, $limit: preloadAmt })
}
haveLoaded.value = true
}
const reset = async () => {
limit.value = increment
await toPage(1)
haveLoaded.value = true
}
const hasMoreComments = computed(() => total.value > limit.value)
return {
data,
hasMoreComments,
haveLoaded,
initial,
loadMore,
reset
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment