feat(frontend): manage API tokens in Frontend

This commit is contained in:
Julian Tölle 2023-02-20 23:50:57 +01:00
parent d0ca2b967e
commit ac0f9ff5d3
13 changed files with 484 additions and 33 deletions

View file

@ -1,11 +1,14 @@
import { useMemo } from "react";
import { useCallback, useMemo } from "react";
import {
createApiToken,
getApiTokens,
getListensReport,
getRecentListens,
getTopAlbums,
getTopArtists,
getTopGenres,
getTopTracks,
revokeApiToken,
} from "../api/api";
import { ListenReportOptions } from "../api/entities/listen-report-options";
import { PaginationOptions } from "../api/entities/pagination-options";
@ -124,3 +127,38 @@ export const useTopGenres = (options: TopGenresOptions) => {
return { topGenres, isLoading, error };
};
export const useApiTokens = () => {
const { client } = useApiClient();
const fetchData = useMemo(() => () => getApiTokens(client), [client]);
const {
value: apiTokens,
pending: isLoading,
error,
reload,
} = useAsync(fetchData, INITIAL_EMPTY_ARRAY);
const createToken = useCallback(
async (description: string) => {
const apiToken = await createApiToken(description, client);
console.log("apiToken created", apiToken);
await reload();
console.log("reloaded data");
return apiToken;
},
[client, reload]
);
const revokeToken = useCallback(
async (id: string) => {
await revokeApiToken(id, client);
await reload();
},
[client, reload]
);
return { apiTokens, isLoading, error, createToken, revokeToken };
};

View file

@ -0,0 +1,26 @@
import React, { useEffect } from "react";
/**
* Hook that alerts clicks outside of the passed ref
*/
export const useOutsideClick = (
ref: React.MutableRefObject<any>,
callback: () => void
) => {
useEffect(() => {
/**
* Alert if clicked on outside of element
*/
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target)) {
callback();
}
};
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref, callback]);
};