Skip to content

Instantly share code, notes, and snippets.

@prpanto
Last active December 13, 2022 13:55
Show Gist options
  • Save prpanto/bd3bb2d9b0cb1fd8afe55f94335891de to your computer and use it in GitHub Desktop.
Save prpanto/bd3bb2d9b0cb1fd8afe55f94335891de to your computer and use it in GitHub Desktop.
Infinity loading in InertiaJS and VueJS
<template>
<template v-for="post in allPosts" :key="post.id">
<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
</template>
<span ref="loadMore"/>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { Inertia } from '@inertiajs/inertia';
import { useIntersectionObserver } from '@vueuse/core'
const props = defineProps({
posts: Object
});
const allPosts = ref(props.posts.data);
const loadMore = ref();
function loadMorePosts() {
if (props.posts.next_page_url === null) return
Inertia.get(props.posts.next_page_url, {}, {
preserveState: true,
preserveScroll: true,
only: ['posts'],
onSuccess: () => {
allPosts.value = [...allPosts.value, ...props.posts.data];
window.history.replaceState({}, page.title, "/post");
}
});
}
onMounted(() => useIntersectionObserver(
loadMore.value,
([{ isIntersecting }]) => isIntersecting && loadMorePosts(),
{ rootMargin: "-150px 0px 0px 0px" }
));
</script>
public function index() {
$posts = Post::paginate(10);
return Inercia::render('Posts/INdex', ['posts', => $posts]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment