My UI won't update even though I successfully receive response

I have this code below I successfully get the response but the UI won't update I still see no data available
<script setup lang="ts">
import { ref } from 'vue';

const name = ref('');
const number = ref(0);
const data = ref([]);

async function submit() {
try {

const response = await $fetch('/api/data', {
method: 'POST',
body: { test: 123, name: name.value, number: number.value },
});

console.log("Response from API:", response);

data.value = Array.isArray(response) ? response : [response];

console.log("Updated data:", data.value);
} catch (error) {
console.error("Error fetching data:", error);
data.value = [];
}
}
</script>

<template>
<input type="number" v-model.number="number" placeholder="Enter a number" />
<input type="text" v-model.trim="name" placeholder="Enter a name" />
<button @click="submit">Submit</button>


<div v-if="data.value && data.value.length > 0">
<div v-for="(da, index) in data" :key="index">
<p>{{ da.test || da }}</p>
</div>
</div>

<div v-else>
<p>No data available</p>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';

const name = ref('');
const number = ref(0);
const data = ref([]);

async function submit() {
try {

const response = await $fetch('/api/data', {
method: 'POST',
body: { test: 123, name: name.value, number: number.value },
});

console.log("Response from API:", response);

data.value = Array.isArray(response) ? response : [response];

console.log("Updated data:", data.value);
} catch (error) {
console.error("Error fetching data:", error);
data.value = [];
}
}
</script>

<template>
<input type="number" v-model.number="number" placeholder="Enter a number" />
<input type="text" v-model.trim="name" placeholder="Enter a name" />
<button @click="submit">Submit</button>


<div v-if="data.value && data.value.length > 0">
<div v-for="(da, index) in data" :key="index">
<p>{{ da.test || da }}</p>
</div>
</div>

<div v-else>
<p>No data available</p>
</div>
</template>
6 Replies
kapa.ai
kapa.ai3w ago
Hi @Revaycolizer. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Based on the code you've provided and the information from the knowledge sources, I can see why your UI isn't updating even though you're receiving a response. The issue is related to how you're fetching and handling the data in Nuxt. Let me explain the problem and suggest a solution. The main issue is that you're using $fetch directly in your component's submit function. While this does make the API call, it doesn't integrate with Nuxt's reactivity system in the same way that useFetch or useAsyncData would. As mentioned in the Nuxt documentation (https://nuxt.com/docs/getting-started/data-fetching#the-need-for-usefetch-and-useasyncdata), using $fetch alone can cause issues with reactivity and hydration. To fix this, you should use useFetch or useAsyncData combined with $fetch. Here's how you can modify your code to make it work:
<script setup lang="ts">
import { ref } from 'vue';

const name = ref('');
const number = ref(0);
const { data, refresh } = await useAsyncData('apiData', () => $fetch('/api/data'));

async function submit() {
try {
await $fetch('/api/data', {
method: 'POST',
body: { test: 123, name: name.value, number: number.value },
});

// Refresh the data after submitting
await refresh();

console.log("Updated data:", data.value);
} catch (error) {
console.error("Error fetching data:", error);
}
}
</script>

<template>
<input type="number" v-model.number="number" placeholder="Enter a number" />
<input type="text" v-model.trim="name" placeholder="Enter a name" />
<button @click="submit">Submit</button>

<div v-if="data && data.length > 0">
<div v-for="(da, index) in data" :key="index">
<p>{{ da.test || da }}</p>
</div>
</div>

<div v-else>
<p>No data available</p>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';

const name = ref('');
const number = ref(0);
const { data, refresh } = await useAsyncData('apiData', () => $fetch('/api/data'));

async function submit() {
try {
await $fetch('/api/data', {
method: 'POST',
body: { test: 123, name: name.value, number: number.value },
});

// Refresh the data after submitting
await refresh();

console.log("Updated data:", data.value);
} catch (error) {
console.error("Error fetching data:", error);
}
}
</script>

<template>
<input type="number" v-model.number="number" placeholder="Enter a number" />
<input type="text" v-model.trim="name" placeholder="Enter a name" />
<button @click="submit">Submit</button>

<div v-if="data && data.length > 0">
<div v-for="(da, index) in data" :key="index">
<p>{{ da.test || da }}</p>
</div>
</div>

<div v-else>
<p>No data available</p>
</div>
</template>
In this modified version: 1. We use useAsyncData to fetch the initial data and create a reactive data ref. 2. In the submit function, we still use $fetch to send the POST request. 3. After the POST request, we call refresh() to update the data. 4. The template now uses data directly instead of data.value. This approach ensures that the data is properly reactive and that the UI will update when the data changes. The refresh function, provided by useAsyncData, allows you to refetch the data and update the UI accordingly. If you're still experiencing issues after making these changes, you might want to try using refreshNuxtData() as mentioned in this Stack Overflow answer (https://stackoverflow.com/questions/77281692). You could add refreshNuxtData() at the end of your submit function:
async function submit() {
// ... existing code ...
await refresh();
refreshNuxtData();
}
async function submit() {
// ... existing code ...
await refresh();
refreshNuxtData();
}
This should ensure that all Nuxt data is refreshed and your UI updates correctly. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3w ago
<@1038884482058563627> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Revaycolizer
RevaycolizerOP3w ago
But below is my API seems it cannot apply to the code you wrote
export default defineEventHandler(async (event) => {
const body = await readBody(event)

const { test, name } = body
if (!test||!name){
return []
}
setResponseStatus(event, 202)

const data =[
{
id:1,
test: test,
name: name
}
]
return data
})
export default defineEventHandler(async (event) => {
const body = await readBody(event)

const { test, name } = body
if (!test||!name){
return []
}
setResponseStatus(event, 202)

const data =[
{
id:1,
test: test,
name: name
}
]
return data
})
@kapa.ai
kapa.ai
kapa.ai3w ago
Let me check the knowledge base for you again. One moment! :books: Sorry @Revaycolizer, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Revaycolizer
RevaycolizerOP3w ago
await refreshNuxtData() works
Cue
Cue3w ago
Any reason why you’re using .value in your template?
Want results from more Discord servers?
Add your server