Currently, I am in the process of developing an application using Nuxt 3 and implementing the Composition API for handling async data. The specific scenario I am facing is this: I have a page that displays articles fetched from the database using useLazyFetch()
. Each article has its own dedicated page stored in a single file named projects/[project].vue
.
Below is the code snippet for projects/[project].vue
:
<script setup lang="ts">
const route = useRoute();
const projectName = route.params.project;
const { pending, data } = useLazyFetch("/api/project", { params: { name: projectName } });
const state = reactive({
title: data.value?.project?.title ?? '',
});
</script>
<template>
<div>
<h1>{{ state.title }}</h1>
<input v-model="state.title" />
</div>
</template>
Although this setup works fine initially, I encounter an issue when I switch back to the main page to select a different article. The data remains unchanged, causing the content of the first viewed article to persist even when navigating to other articles.
NOTE:
data.value.project
can be null.
I attempted to address this by incorporating refresh
:
<script setup lang="ts">
const route = useRouter();
const projectName = route.params.project;
const { pending, data, refresh } = useLazyFetch("/api/project", { params: { name: projectName } });
const state = reactive({
title: data.value?.project?.title ?? '',
});
watchEffect(async () => {
if (!pending.value && data.value.project != null) {
if (projectName !== data.value.project.id) {
await refresh();
}
}
});
</script>
<template>
<div>
<h1>{{ state.title }}</h1>
<input v-model="state.title" />
</div>
Despite my attempts with the above method, there was no noticeable change in the behavior.
NOTE: Switching from
reactive
toref
didn't yield any difference.
NOTE: Implementing
useFetch
did not provide a solution either.
NOTE: Trying out
useLazyAsyncData
also did not resolve the issue.
In conclusion, I am seeking guidance on how to update the default values within reactive()
when utilizing the Composition API.