My journey with nuxt3 is still new. I am currently working on developing a new API-based app with nuxt3. Previous versions seemed to work "somehow," but they did not meet my expectations. Here are the things I am looking to cover, both in theory and in code:
1. Create a typed "container" for storage that can be used to track the current state of the form.
# types/models.ts
export type Client = {
id?: number;
name: string;
}
# The ID is optional as the container can be used for new records as well, which do not have an ID yet.
I have imported this in my view:
<script setup lang="ts">
import { Client } from '~/types/models'
const { auth } = useSupabaseAuthClient();
const { data: { session } } = await auth.getSession()
const route = useRoute();
# I am struggling to assign the type to use it in the views successfully.
const client = ref<Client>({
name: "a",
});
# Since the result attributes are wrapped in "client" in the response, I have used the following interface
interface TransformedData {
client: Client
}
const { data:result } = await useFetch(`http://localhost:3000/clients/${route.params.id}`, {
headers: {
'Authorization': `Bearer ${session?.access_token}`
},
transform: (result) => (result as TransformedData).client,
});
# I am struggling to pass the result correctly to the client.
client.value = await(result.value as Client);
const submitForm = async () => {
const { data:result } = await useFetch(`http://localhost:3000/clients/${route.params.id}`, {
method: "PATCH",
body: {
client: {
name: client.value.name,
}
},
headers: {
'Authorization': `Bearer ${session?.access_token}`
},
transform: (result) => (result as TransformedData).client,
});
// client.name = (result.value as Client).name;
}
</script>
<template>
<form @submit.prevent="submitForm">
<input v-model="client.name" type="text" name="name" id="name" />
<button type="submit">Save</button>
</form>
</template>
Essentially, I am looking for best practices to achieve the following:
- Establish a "store" in the view (apologies for incorrect wording)
- Retrieve data from a GET request and populate the store
- Display the form and other elements on the page using the store data
- Send a PATCH request using the "store" to update the server and refresh the view
Since this serves as the foundation for all other views, I am eager to have a well-thought-out implementation that makes sense, as opposed to just "somehow unexpectedly working" as I previously experienced.
Things I have attempted
- Wrapped the GET request in a const loadData and called it onMounted, but it did not work.
- Used useAsyncData and $fetch, encountered the same issues.
- Explored various syntax and approaches throughout the code, but none seemed to work.
- Scoured the depths of the internet for solutions.
If anyone has a best practice to share or ideas on how to tackle this, I would greatly appreciate it!
Thank you in advance!