Reputation: 1564
I am new with Composition API 3 and trying to call an API and show data in page
My code is like this:
let items: IChannel[] = reactive([]);
async function get() {
try {
const res = await channelService.get()
console.log(res)
items = res.data;
} catch (err) {
console.log(err)
Swal.fire("error", "error", "error");
}
}
and it successfully gets data from API but doesn't show in template:
<template>
{{ items }}
</template>
Where is the problem?
Upvotes: 0
Views: 287
Reputation: 138276
You're overwriting items
(a reactive
instance) with the raw data, which removes its reactivity:
let items: IChannel[] = reactive([]);
ā®
items = res.data; ā overwrites `reactive`
reactive
Use a reactive
object that receives the raw data:
š
const items = reactive({ items: [] as IChannel[] });
async function get() {
try {
const res = await channelService.get()
š
items.items = res.data;
} catch (err) {
//...
}
}
ref
Use a ref
instead of reactive
, making sure to set its value
property with the newly received raw data:
š
const items = ref([] as IChannel[])
async function get() {
try {
const res = await channelService.get()
š
items.value = res.data;
} catch (err) {
//...
}
}
Upvotes: 1