Problem setting awaited value to state #2058
-
I'm trying to implement a store with a generic value and set a value returned from an api call. This is my store export const useAuthStore = <T = AuthUserResource>({ typeGuard = isAuthUserResource }: { typeGuard?: <T>(user: unknown) => user is T } = {}) => {
const service = useAuthService<T>({ typeGuard })
return defineStore('auth', {
state: () => ({
user: {} as T
}),
actions: {
set(u: UnwrapRef<T>) {
this.user = u
},
async login(body: LoginRequest) {
const data = await service.login({ body })
if (typeGuard<T>(data)) this.user = data
}
},
getters: {
isAuthenticated: (state) => typeGuard<T>(state.user) ?? false
}
})
} and the service is export const useAuthService = <T = AuthUserResource>({typeGuard = isAuthUserResource}: { typeGuard?: <T>(user: unknown) => user is T } = {}) => {
const {post} = apiWrapper({prefix: API_URL})
const login = async ({body}: { body: LoginRequest }): Promise<T | undefined> => {
const data = await post({ url: LOGIN_URL, body: JSON.stringify(body) })
return isDetailResponse(data) && typeGuard(data.data) ? data.data : undefined
}
return {
login,
}
} Typeguard function export const isAuthUserResource = <T = AuthUserResource>(user: unknown): user is T => {
return typeof user === 'object' &&
user !== null &&
'id' in user &&
'name' in user &&
'email' in user
} This is the error i'm getting.
Simple reproduction in store/main.ts: |
Beta Was this translation helpful? Give feedback.
Answered by
andredewaard
Mar 7, 2023
Replies: 1 comment
-
Fixed by updating the type provided to the useAuthService to also return a export const useAuthStore = <T = AuthUserResource>({ typeGuard = isAuthUserResource }: { typeGuard?: <T>(user: unknown) => user is T } = {}) => {
const service = useAuthService<UnwrapRef<T>>({ typeGuard })
return defineStore('auth', {
state: () => ({
user: {} as T
}),
actions: {
set(u: UnwrapRef<T>) {
this.user = u
},
async login(body: LoginRequest) {
const data = await service.login({ body })
if (typeGuard<T>(data)) this.user = data
}
},
getters: {
isAuthenticated: (state) => typeGuard<T>(state.user) ?? false
}
})
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
andredewaard
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed by updating the type provided to the useAuthService to also return a
unwrapref<T>
instead of just<T>