Pinia store contains null values if referenced from onMounted hook

I’m having an issue where my Pinia store will contain null for each of its state properties if I try to access it via onMounted hook. It’s a little more complex than that. Here is the call stack basically

  • Component (OnMounted) calls
  • Composable calls
  • Pinia Store

Component

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>onMounted(async () => {
const resp = await $authFetch(config.functionsBaseUrl + 'v1/account/settings',
{
method: 'GET'
}).catch(e => {
toast.show({
type: 'error',
title: 'Error',
content: e.data
});
return null;
})
if (resp === null)
return;
userSetings.value = resp;
})
</code>
<code>onMounted(async () => { const resp = await $authFetch(config.functionsBaseUrl + 'v1/account/settings', { method: 'GET' }).catch(e => { toast.show({ type: 'error', title: 'Error', content: e.data }); return null; }) if (resp === null) return; userSetings.value = resp; }) </code>
onMounted(async () => {
    const resp = await $authFetch(config.functionsBaseUrl + 'v1/account/settings',
    {
        method: 'GET'
    }).catch(e => {
        toast.show({
            type: 'error',
            title: 'Error',
            content: e.data
        });

        return null;
    })

    if (resp === null)
    return;

    userSetings.value = resp;
})

Composable

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export async function $authFetch<T>(
request: Parameters<typeof $fetch<T>>[0],
opts?: Parameters<typeof $fetch<T>>[1],
) {
const auth = useAuth(useNuxtApp().$pinia);
const shouldRefreshToken = () => {
const currentTime = Math.floor(Date.now() / 1000);
// Calculate the time difference between expiration time and current time
console.log('calculating', auth.tokenExpiration);
const timeDifference = auth.tokenExpiration - currentTime;
console.log('time diff', timeDifference);
// Check if the token is expiring within the next 5 minutes (300 seconds)
return timeDifference <= 300;
}
console.log('authFetch', auth, auth.tokenExpiration, shouldRefreshToken());
if (auth.tokenExpiration && shouldRefreshToken()) {
const url = useRuntimeConfig().public.functionsBaseUrl + 'v1/auth/refresh';
console.log('refreshing', url);
const resp = await $fetch(url, {
method: 'POST',
body: {
refreshToken: auth.refreshToken,
idToken: auth.token
},
headers: {
Authorization: `Bearer ${auth.token}`
}
}).catch(e => {
if (e.data === 'Unauthorized') {
//refresh token has expired, log the user out
auth.$reset();
const cookie = useCookie('auth');
cookie.value = null;
}
});
auth.token = resp.Token;
auth.tokenExpiration = resp.Expiration;
}
return $fetch<T>(request, {
...opts,
headers: {
Authorization: `Bearer ${auth.token}`,
...opts?.headers,
},
});
}
</code>
<code>export async function $authFetch<T>( request: Parameters<typeof $fetch<T>>[0], opts?: Parameters<typeof $fetch<T>>[1], ) { const auth = useAuth(useNuxtApp().$pinia); const shouldRefreshToken = () => { const currentTime = Math.floor(Date.now() / 1000); // Calculate the time difference between expiration time and current time console.log('calculating', auth.tokenExpiration); const timeDifference = auth.tokenExpiration - currentTime; console.log('time diff', timeDifference); // Check if the token is expiring within the next 5 minutes (300 seconds) return timeDifference <= 300; } console.log('authFetch', auth, auth.tokenExpiration, shouldRefreshToken()); if (auth.tokenExpiration && shouldRefreshToken()) { const url = useRuntimeConfig().public.functionsBaseUrl + 'v1/auth/refresh'; console.log('refreshing', url); const resp = await $fetch(url, { method: 'POST', body: { refreshToken: auth.refreshToken, idToken: auth.token }, headers: { Authorization: `Bearer ${auth.token}` } }).catch(e => { if (e.data === 'Unauthorized') { //refresh token has expired, log the user out auth.$reset(); const cookie = useCookie('auth'); cookie.value = null; } }); auth.token = resp.Token; auth.tokenExpiration = resp.Expiration; } return $fetch<T>(request, { ...opts, headers: { Authorization: `Bearer ${auth.token}`, ...opts?.headers, }, }); } </code>
export async function $authFetch<T>(
    request: Parameters<typeof $fetch<T>>[0],
    opts?: Parameters<typeof $fetch<T>>[1],
) {
    const auth = useAuth(useNuxtApp().$pinia);

    const shouldRefreshToken = () => {
        const currentTime = Math.floor(Date.now() / 1000);

        // Calculate the time difference between expiration time and current time
        console.log('calculating', auth.tokenExpiration);
        const timeDifference = auth.tokenExpiration - currentTime;
        console.log('time diff', timeDifference);
        // Check if the token is expiring within the next 5 minutes (300 seconds)
        return timeDifference <= 300;
    }

    console.log('authFetch', auth, auth.tokenExpiration, shouldRefreshToken());

    if (auth.tokenExpiration && shouldRefreshToken()) {
        const url = useRuntimeConfig().public.functionsBaseUrl + 'v1/auth/refresh';
        console.log('refreshing', url);
        const resp = await $fetch(url, {
            method: 'POST',
            body: {
                refreshToken: auth.refreshToken,
                idToken: auth.token
            },
            headers: {
                Authorization: `Bearer ${auth.token}`
            }
        }).catch(e => {
            if (e.data === 'Unauthorized') {
                //refresh token has expired, log the user out
                auth.$reset();
                const cookie = useCookie('auth');
                cookie.value = null;
            }
        });

        auth.token = resp.Token;
        auth.tokenExpiration = resp.Expiration;
    }

    return $fetch<T>(request, {
        ...opts,
        headers: {
            Authorization: `Bearer ${auth.token}`,
            ...opts?.headers,
        },
    });
}

Store

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export const useAuth = defineStore('auth', {
state: () => ({
token: null,
refreshToken: null,
email: null,
userId: null,
firstName: null,
lastName: null,
organizationId: null,
organizationName: null,
organizationIndustry: null,
tokenExpiration: null
}),
actions: {
setLoginPayload(loginResponse) {
this.token = loginResponse.Token;
this.refreshToken = loginResponse.RefreshToken;
this.email = loginResponse.Email;
this.userId = loginResponse.UserId;
this.firstName = loginResponse.FirstName;
this.lastName = loginResponse.LastName;
this.organizationId = loginResponse.OrganizationId;
this.organizationName = loginResponse.CompanyName;
this.organizationIndustry = loginResponse.Industry;
this.tokenExpiration = loginResponse.Expiration;
console.log('set token expiration', loginResponse.Expiration);
//set in localstorage
const cookie = useCookie('auth');
cookie.value = loginResponse;
}
}
})
</code>
<code>export const useAuth = defineStore('auth', { state: () => ({ token: null, refreshToken: null, email: null, userId: null, firstName: null, lastName: null, organizationId: null, organizationName: null, organizationIndustry: null, tokenExpiration: null }), actions: { setLoginPayload(loginResponse) { this.token = loginResponse.Token; this.refreshToken = loginResponse.RefreshToken; this.email = loginResponse.Email; this.userId = loginResponse.UserId; this.firstName = loginResponse.FirstName; this.lastName = loginResponse.LastName; this.organizationId = loginResponse.OrganizationId; this.organizationName = loginResponse.CompanyName; this.organizationIndustry = loginResponse.Industry; this.tokenExpiration = loginResponse.Expiration; console.log('set token expiration', loginResponse.Expiration); //set in localstorage const cookie = useCookie('auth'); cookie.value = loginResponse; } } }) </code>
export const useAuth = defineStore('auth', {
    state: () => ({
        token: null,
        refreshToken: null,
        email: null,
        userId: null,
        firstName: null,
        lastName: null,
        organizationId: null,
        organizationName: null,
        organizationIndustry: null,
        tokenExpiration: null
    }),
    actions: {
        setLoginPayload(loginResponse) {
            this.token = loginResponse.Token;
            this.refreshToken = loginResponse.RefreshToken;
            this.email = loginResponse.Email;
            this.userId = loginResponse.UserId;
            this.firstName = loginResponse.FirstName;
            this.lastName = loginResponse.LastName;
            this.organizationId = loginResponse.OrganizationId;
            this.organizationName = loginResponse.CompanyName;
            this.organizationIndustry = loginResponse.Industry;
            this.tokenExpiration = loginResponse.Expiration;
            console.log('set token expiration', loginResponse.Expiration);

            //set in localstorage
            const cookie = useCookie('auth');
            cookie.value = loginResponse;
        }
    }
})

If I wrap the code inside the onMounted function in a 1 second delay, the store values are no longer empty

I can’t find anything anywhere that explains that Pinia needs some time to “be ready” or a way to await it to “be ready”

Is there anything obvious here why my store is empty when called in onMount?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật