From d86016ba48346be91aeace3c75bb7d990badafe8 Mon Sep 17 00:00:00 2001 From: Topvennie Date: Sun, 11 Aug 2024 12:07:07 +0200 Subject: [PATCH] vinvoor: auto redirect to login page --- vinvoor/src/hooks/useFetch.ts | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/vinvoor/src/hooks/useFetch.ts b/vinvoor/src/hooks/useFetch.ts index c26ac0b..eee5f03 100644 --- a/vinvoor/src/hooks/useFetch.ts +++ b/vinvoor/src/hooks/useFetch.ts @@ -1,5 +1,12 @@ -import { Dispatch, SetStateAction, useEffect, useState } from "react"; -import { getApi } from "../util/fetch"; +import { + Dispatch, + SetStateAction, + useContext, + useEffect, + useState, +} from "react"; +import { UserContext } from "../providers/UserProvider"; +import { getApi, isResponseNot200Error } from "../util/fetch"; interface useFetchResult { loading: boolean; @@ -14,10 +21,25 @@ export const useFetch = ( const [loading, setLoading] = useState(true); const [error, setError] = useState(undefined); + const { setUserState } = useContext(UserContext); + useEffect(() => { getApi(endpoint, convertData) .then((data) => setData(data)) - .catch((error) => setError(error)) + .catch((error) => { + if ( + isResponseNot200Error(error) && + error.response.status === 401 + ) { + setUserState({ + user: undefined, + loading: false, + error: error, + }); + } + + setError(error); + }) .finally(() => setLoading(false)); }, [endpoint]);