Skip to content

Commit

Permalink
fix: media won't load when token needs refreshing (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
sverben authored Jul 2, 2024
1 parent c1de93b commit fab5bc1
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ interface GuestState {
authenticated: Authed.GUEST;
login: () => void;
}
type AuthState =
export type AuthState =
| AuthenticatedState
| UnAuthenticatedState
| LoadingState
Expand Down
6 changes: 2 additions & 4 deletions src/screens/media/media.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ enum Page {

export default function MediaScreen() {
const authState = useContext(AuthContext);
const [api, setApi] = useAtom(apiAtom);
const [_api, setApi] = useAtom(apiAtom);
const [page, setPage] = useState<Page>(Page.ALBUMS);
const theme = useTheme();

Expand All @@ -24,9 +24,7 @@ export default function MediaScreen() {
return setApi(null);
}

authState.token.then((token) => {
setApi(getApi(token));
});
setApi(getApi(authState));
}, [authState]);

return (
Expand Down
18 changes: 14 additions & 4 deletions src/stores/media.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
import { atom } from "jotai";
import { Api } from "../__generated__/media";
import { Authed, AuthState } from "../auth";

export const apiAtom = atom<Api<unknown> | null>(null);
export function getApi(token: string) {
export function getApi(authState: AuthState) {
return new Api({
baseUrl: "https://media.djoamersfoort.nl/api",
baseApiParams: {
credentials: "same-origin",
headers: {
authorization: `Bearer ${token}`,
},
redirect: "follow",
referrerPolicy: "no-referrer",
},
async customFetch(...fetchParams: Parameters<typeof fetch>) {
if (authState.authenticated !== Authed.AUTHENTICATED)
throw new Error("Unauthenticated");
if (!fetchParams[1]) fetchParams[1] = {};
if (!fetchParams[1].headers) fetchParams[1].headers = {};

Object.assign(fetchParams[1].headers, {
authorization: `Bearer ${await authState.token}`,
});

return fetch(...fetchParams);
},
});
}

0 comments on commit fab5bc1

Please sign in to comment.