Encountering challenges in my Vue 3 app when trying to update a component's state post an asynchronous operation. Here's what's happening:
Within a component, there is a method called containerMoveHere that utilizes Socket.io for an async operation to move a container, which then gets added to the list of displayed containers. Following a successful move, I aim to update the children array in my Pinia store and trigger a re-render of the component to reflect this change.
Here's the snippet of code:
page.vue
<template>
...
<div class="flex justify-end space-x-2">
<MoveToHereButton @click.prevent="containerMoveHere()" />
</div>
...
<div class="grid grid-cols-3 gap-4 py-6 place-content-stretch">
<div v-for="child in children" :key="child._id">
<ContainerCard :container="child" />
</div>
</div>
...
</template>
<script setup lang="ts">
const userStore = useUserStore();
const containerStore = useContainerStore()
const container = storeToRefs(containerStore).container;
const children = storeToRefs(containerStore).visibleChildren;
async function containerMoveHere() {
try {
let containerStrId = await userStore.getContainerIdToMove();
await containerStore.containerMoveHere(containerStrId)
} catch (error) {
console.error(error)
}
}
</script>
And here's the corresponding store:
export const useContainerStore = defineStore('container', {
state: () => {
let container: iContainerAllType | undefined;
const children: Array<{ visible: boolean; data: iContainerAllType }> = [];
return {
container, children
};
},
getters: {
visibleChildren(): Array<iContainerAllType> {
return this.children.filter(c => c.visible).map(c => c.data);
}
},
actions: {
async containerMoveHere(sourceContainerStrId) {
try {
await socketioservice.emit('container:moveTo', {
container: {
Id: this.container?._id,
Space: this.container?._space,
SourceId: sourceContainerStrId
}
});
} catch (error) {
console.error('Error moving container:', error);
}
},
}
Additional info:
The container successfully moves, and reloading the page displays the added container within the children as expected. However, the issue lies in the fact that the children state does not update despite being a reactive property.
Appreciate any assistance you can provide on this matter.