File tree Expand file tree Collapse file tree 2 files changed +7
-5
lines changed Expand file tree Collapse file tree 2 files changed +7
-5
lines changed Original file line number Diff line number Diff line change
1
+ import { useAuthStore } from '@/stores' ;
2
+
1
3
export const fetchWrapper = {
2
4
get : request ( 'GET' ) ,
3
5
post : request ( 'POST' ) ,
@@ -23,7 +25,7 @@ function request(method) {
23
25
24
26
function authHeader ( url ) {
25
27
// return auth header with jwt if user is logged in and request is to the api url
26
- const user = JSON . parse ( localStorage . getItem ( 'user' ) ) ;
28
+ const { user } = useAuthStore ( ) ;
27
29
const isLoggedIn = ! ! user ?. token ;
28
30
const isApiUrl = url . startsWith ( import . meta. env . VITE_API_URL ) ;
29
31
if ( isLoggedIn && isApiUrl ) {
@@ -38,10 +40,10 @@ function handleResponse(response) {
38
40
const data = text && JSON . parse ( text ) ;
39
41
40
42
if ( ! response . ok ) {
41
- if ( [ 401 , 403 ] . includes ( response . status ) && localStorage . getItem ( 'user' ) ) {
43
+ const { user, logout } = useAuthStore ( ) ;
44
+ if ( [ 401 , 403 ] . includes ( response . status ) && user ) {
42
45
// auto logout if 401 Unauthorized or 403 Forbidden response returned from api
43
- localStorage . removeItem ( 'user' ) ;
44
- location . href = '/login' ;
46
+ logout ( ) ;
45
47
}
46
48
47
49
const error = ( data && data . message ) || response . statusText ;
Original file line number Diff line number Diff line change @@ -14,7 +14,7 @@ usersStore.getAll();
14
14
15
15
<template >
16
16
<div >
17
- <h1 >Hi {{authUser.firstName}}!</h1 >
17
+ <h1 >Hi {{authUser? .firstName}}!</h1 >
18
18
<p >You're logged in with Vue 3 + Pinia & JWT!!</p >
19
19
<h3 >Users from secure api end point:</h3 >
20
20
<ul v-if =" users.length" >
You can’t perform that action at this time.
0 commit comments