I have a Pinia + TypeScript store named user.ts that looks like this:
import { User } from 'firebase/auth';
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () =>
({
displayName: null,
email: null,
emailVerified: null,
isAnonymous: null,
metadata: null,
multiFactor: null,
phoneNumber: null,
photoURL: null,
providerData: null,
providerId: null,
refreshToken: null,
tenantId: null,
uid: null,
} as unknown as User),
actions: {
setPhotoURL(photoURLData: string | null) {
this.photoURL = photoURLData; //<-- ERROR HERE
},
},
});
The state is a FireBase User object.
And I want to update photoURL using the setPhotoURL() action.
But photoURL has this TypeScript error:
Cannot assign to 'photoURL' because it is a read-only property. ts(2540)
What am I doing wrong?
Is this the correct way to update state?
>Solution :
'firebase/auth' declares User interface as having readonly props. When you forcefully apply that interface to your state object, TS trusts you.
Spreading it should remove the readonly from its props, while still inferring the types:
export const useUserStore = defineStore('user', {
state: () => ({ ...({
displayName: null,
email: null,
emailVerified: null,
isAnonymous: null,
metadata: null,
multiFactor: null,
phoneNumber: null,
photoURL: null,
providerData: null,
providerId: null,
refreshToken: null,
tenantId: null,
uid: null,
} as unknown as User) }),
actions: {
//...
}
})