Skip to content

Commit

Permalink
Merge pull request #77 from manchenkoff/69-user-is-requested-on-every…
Browse files Browse the repository at this point in the history
…-page

fix: prevent multiple identity requests on init
  • Loading branch information
manchenkoff authored Apr 17, 2024
2 parents 0d58e6e + cc76b0e commit 36c6b13
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"test": "vitest run",
"test:watch": "vitest watch",
"validate": "npm run fmt:check && npm run lint && npm run types && npm run test",
"release": "npm run validate && npm run prepack && changelogen --release && npm publish"
"release": "npm run validate && npm run prepack && changelogen --release && npm publish && git push"
},
"dependencies": {
"@nuxt/kit": "^3.9.0",
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/httpFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ export function createHttpClient(logger: ConsolaInstance): $Fetch {

if (
response.status === 401 &&
request.toString().endsWith(options.endpoints.user)
request.toString().endsWith(options.endpoints.user) &&
user.value !== null
) {
logger.warn(
'User session is not set in API or expired, resetting identity'
Expand Down
11 changes: 9 additions & 2 deletions src/runtime/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FetchError } from 'ofetch';
import { defineNuxtPlugin } from '#app';
import { defineNuxtPlugin, useState } from '#app';
import { createHttpClient } from './httpFactory';
import { useSanctumUser } from './composables/useSanctumUser';
import { useSanctumConfig } from './composables/useSanctumConfig';
Expand Down Expand Up @@ -34,7 +34,14 @@ export default defineNuxtPlugin(async () => {
const logger = createSanctumLogger(options.logLevel);
const client = createHttpClient(logger);

if (user.value === null) {
const identityFetchedOnInit = useState<boolean>(
'sanctum.user.loaded',
() => false
);

if (user.value === null && identityFetchedOnInit.value === false) {
identityFetchedOnInit.value = true;

try {
user.value = await client(options.endpoints.user);
} catch (error) {
Expand Down

0 comments on commit 36c6b13

Please sign in to comment.