From 6c298a5da589490562d9fd58e30851cd63d398b5 Mon Sep 17 00:00:00 2001 From: KimiaMontazeri Date: Thu, 30 Nov 2023 15:44:51 +0330 Subject: [PATCH] fix: show error to unauthorized user trying to add item to cart --- .../src/providers/APIProvider/APIProvider.jsx | 43 +++++++++++-------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/frontend/src/providers/APIProvider/APIProvider.jsx b/frontend/src/providers/APIProvider/APIProvider.jsx index e36b4ad..1f6c9f2 100644 --- a/frontend/src/providers/APIProvider/APIProvider.jsx +++ b/frontend/src/providers/APIProvider/APIProvider.jsx @@ -172,22 +172,27 @@ export function APIProvider({ children }) { break; } - const tokenStr = JSON.parse(localStorage.getItem('user'))['access']; - await service - .post(`${URL.baseURL}${URL.services.default}${endpoint}`, body, { - headers: { Authorization: `Bearer ${tokenStr}` }, - }) - .then((response) => { - setAddToCartResponse(response); - }) - .catch((error) => { - setAddToCartResponse(error.response); - if (!error) return; - - if (error.response.status === 401) { - updateAccessTokenWithRefreshToken(); - } - }); + const userKey = JSON.parse(localStorage.getItem('user')); + if (userKey == null) { + setAddToCartResponse({ status: 401 }); + } else { + const tokenStr = userKey.access; + await service + .post(`${URL.baseURL}${URL.services.default}${endpoint}`, body, { + headers: { Authorization: `Bearer ${tokenStr}` }, + }) + .then((response) => { + setAddToCartResponse(response); + }) + .catch((error) => { + setAddToCartResponse(error.response); + if (!error) return; + + if (error.response.status === 401) { + updateAccessTokenWithRefreshToken(); + } + }); + } }, [service], ); @@ -235,9 +240,9 @@ export function APIProvider({ children }) { .then((response) => { setPaymentData(response); }) - .catch(error => { - setPaymentData(error.response) - }); + .catch((error) => { + setPaymentData(error.response); + }); }, [currentYear, service, getAccessTokenHeader], );