The provided code snippet demonstrates how to fetch and insert more data with Inertia in a Vue template. The code uses a timeout to periodically call the fetchMoreLogs function, which fetches new logs and inserts them at the beginning of the logs array.
To achieve a similar result while staying in line with Inertia and partial page loading, you can use the inertia object's visit method instead of directly calling router.get. Here's an updated version of the code:
<script setup>
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout.vue";
import { Head, usePage } from "@inertiajs/inertia-vue3";
import { ref, computed, onMounted } from "vue";
Head.name = "InertiaHead";
const { props } = usePage();
const logs = ref(props.logs);
const nextForwardToken = ref(props.nextForwardToken);
const logCount = computed(() => {
return logs.value ? logs.value.length : 0;
});
const convertToClientLocalTime = (timestamp) => {
const localDate = new Date(timestamp);
return localDate.toLocaleString(); // You can customize this based on your needs
};
const fetchMoreLogs = () => {
inertia.visit('/logs', {
preserveState: true,
data: { nextForwardToken: nextForwardToken.value },
onSuccess: (page) => {
if (page.props.logs && page.props.logs.length > 0) {
// Insert new logs in the beginning
logs.value = [...page.props.logs, ...logs.value];
nextForwardToken.value = page.props.nextForwardToken;
}
// Run again
setTimeout(fetchMoreLogs, 5000);
},
});
};
onMounted(() => {
// Run once
setTimeout(fetchMoreLogs, 5000);
});
</script>
In this updated code, the inertia object's visit method is used to make the API call. The data property is used to pass the nextForwardToken value to the server. The onSuccess callback is triggered when the API call is successful, and it inserts the new logs at the beginning of the logs array.
Additionally, the onMounted lifecycle hook is used to start the initial fetch after the component is mounted.
Please note that you need to make sure you have the @inertiajs/inertia-vue3 package installed and properly set up in your project for this solution to work.