Skip to content

Commit

Permalink
vinvoor: auto redirect to login page
Browse files Browse the repository at this point in the history
  • Loading branch information
Topvennie authored and hannes-dev committed Aug 12, 2024
1 parent 73cfb4c commit d86016b
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions vinvoor/src/hooks/useFetch.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -14,10 +21,25 @@ export const useFetch = <T>(
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<Error | undefined>(undefined);

const { setUserState } = useContext(UserContext);

useEffect(() => {
getApi<T>(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]);

Expand Down

0 comments on commit d86016b

Please sign in to comment.