Skip to content

Commit cbbf684

Browse files
committed
updated fetch wrapper to use auth store
1 parent 8065742 commit cbbf684

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

src/helpers/fetch-wrapper.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { useAuthStore } from '@/stores';
2+
13
export const fetchWrapper = {
24
get: request('GET'),
35
post: request('POST'),
@@ -23,7 +25,7 @@ function request(method) {
2325

2426
function authHeader(url) {
2527
// 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();
2729
const isLoggedIn = !!user?.token;
2830
const isApiUrl = url.startsWith(import.meta.env.VITE_API_URL);
2931
if (isLoggedIn && isApiUrl) {
@@ -38,10 +40,10 @@ function handleResponse(response) {
3840
const data = text && JSON.parse(text);
3941

4042
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) {
4245
// auto logout if 401 Unauthorized or 403 Forbidden response returned from api
43-
localStorage.removeItem('user');
44-
location.href = '/login';
46+
logout();
4547
}
4648

4749
const error = (data && data.message) || response.statusText;

src/views/HomeView.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ usersStore.getAll();
1414

1515
<template>
1616
<div>
17-
<h1>Hi {{authUser.firstName}}!</h1>
17+
<h1>Hi {{authUser?.firstName}}!</h1>
1818
<p>You're logged in with Vue 3 + Pinia & JWT!!</p>
1919
<h3>Users from secure api end point:</h3>
2020
<ul v-if="users.length">

0 commit comments

Comments
 (0)