I am using Vue 3 with Composition API, a Pinia store, TypeScript, SQL backend and Fetch to grab the data via my .NET 6 API.
I have a User.ts class
export default class User { userName: string | null constructor (userName: string | null) { this.userName = userName; } }
and I Fetch the data from the DB using the below method
getAdminUsers(): void { fetch(apiURL + 'AdminUser', { headers: { "Accept": "application/json", "Content-Type": 'application/json' } }) .then(response => { return response.json(); }) .then(data => { this.$patch((state) => { state.adminUser = { userName: null}; state.adminUsers = []; }) data.forEach((user: User) => { if (user.userName) { this.adminUser = new User(user.userName.toUpperCase()); this.adminUsers.push(this.adminUser); } }) }) },
For all the other data in my app, I have had no issues. However, when I refresh the page, or try run the getAdminUsers method from anywhere in my Vue app, it returns an empty array.
[[Handler]]: Object [[Target]]: Array(0) length: 0 [[Prototype]]: Array(0) [[IsRevoked]]: false
But when I make a tiny change to my app (such as add a space anywhere etc) and save>rebuild, the array is then populated with the correct data.
Proxy {0: User, 1: User} [[Handler]]: Object [[Target]]: Array(2) 0: User {userName: 'GEORGE.SMITHSON'} 1: User {userName: 'TEST.2'} length: 2 [[Prototype]]: Array(0) [[IsRevoked]]: false
I really don’t understand why it is happening and can’t get it to work correctly. Any help is greatly appreciated!
Advertisement
Answer
Hard to say since you do not include how you’re using the array. It definitely sounds as if your array is not reactive for some reason. That would explain why the array is not updating until a hot reload occurs. Are you perhaps assigning it to another variable? Is that variable also reactive? If you are assigning it should be something like this:
const adminStore = useAdminStore(); const adminUsers = computed(() => adminStore.adminUsers);