I am using Typescript on my Vue page and trying to fetch user data from API.
<script setup lang="ts">
const { data: user } = await useFetch('/api/user/info', {
headers: useRequestHeaders(['cookie'])
});
if (!user.value)
throw createError('Problems when fetching current user!');
const myComputed = computed(() => !user.value.login); // <-- Error!
</script>
However I get tons of errors!
When I try to use user.value
in script
I get user.value possibly null
errors and inside template
I get __VLS_ctx.user possibly null
errors.
Errors disappear when I remove lang="ts"
attribute from script
but I don’t want to do this. How to fix this problem?
My API:
export default defineEventHandler(async event => {
const userId = await getTokenUserId(getCookie(event, 'token'));
if (!userId)
return setResponseStatus(event, 403);
const db = await getDb();
const dbUser = await db.manager.findOneBy(User, { id: userId });
if (!dbUser)
return setResponseStatus(event, 404);
return {
login: dbUser.login,
isEditor: dbUser.isEditor,
topics: await getUserTopicsListInfo(userId),
};
});
2
Answers
Null check the value, it might solve the issue?
You can also use the non-null assertion operator !
Using a wrapped
useFetch
method to handle the errors uniformly instead of managing errors separately on each page could be a better practice.This answer will not directly answer your current question but will solve all problems that got unexpected API responses.
define a
useCustomFetch
as a wrappeduseFetch
, which got exactly the same params and return asuseFetch
Now, you add the code before sending and after the response. (just like the interceptors in axios)
What’s more, you don’t need to add the
headers: useRequestHeaders(['cookie'])
each time you useuseFetch
, you can add it once and use it everywhere.After this, you can use
useCustomFetch
to replaceuseFetch