Files
js/@3rdweb-sdk/react/hooks/useApi.ts
T
cb8eca2a0c Add support for API Keys (#1164)
* Add support for API Keys

* Update

* Fix import

* Fix invalidation

* Add a getting started flow

* Fix

* Fix everything

* Remove console.log

* Update

* Logout if there's an address mismatch

* Logout if there's an address mismatch

* Add error messages

* Add wallets

* Escape apostrophe

* Add link to documentation

* Update copy

* rename and added CW button demo

* reorder wallets

---------

Co-authored-by: Nacho Iacovino <[email protected]>
Co-authored-by: Joaquim Verges <[email protected]>
2023-05-04 16:31:17 +00:00

110 lines
2.6 KiB
TypeScript

import { apiKeys } from "../cache-keys";
import { useMutationWithInvalidate } from "./query/useQueryWithNetwork";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useUser } from "@thirdweb-dev/react";
import invariant from "tiny-invariant";
export type ApiKeyInfo = {
creatorWalletAddress: string;
key: string;
revoked: boolean;
};
export function useApiKeys() {
const { user } = useUser();
return useQuery(
apiKeys.keys(user?.address as string),
async () => {
const res = await fetch("https://api.thirdweb.com/v1/dashboard/keys", {
method: "GET",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
});
const data = await res.json();
if (data.error) {
throw new Error(data.error?.message || data.error);
}
const keys = (data.keys as ApiKeyInfo[]).filter((item) => !item.revoked);
return keys;
},
{ enabled: !!user?.address },
);
}
export function useCreateApiKey() {
const { user } = useUser();
const queryClient = useQueryClient();
return useMutation(
async () => {
invariant(user, "No user is logged in");
const res = await fetch("https://api.thirdweb.com/v1/dashboard/keys", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
});
const data = await res.json();
if (data.error) {
throw new Error(data.error?.message || data.error);
}
return data;
},
{
onSuccess: (_data, _variables, _options) => {
return queryClient.invalidateQueries(
apiKeys.keys(user?.address as string),
);
},
},
);
}
export function useRevokeApiKey() {
const { user } = useUser();
const queryClient = useQueryClient();
return useMutationWithInvalidate(
async (key: string) => {
invariant(user, "No user is logged in");
const res = await fetch(
"https://api.thirdweb.com/v1/dashboard/keys/revoke",
{
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
key,
}),
},
);
const data = await res.json();
if (data.error) {
throw new Error(data.error?.message || data.error);
}
return data;
},
{
onSuccess: (_data, _variables, _options) => {
return queryClient.invalidateQueries(
apiKeys.keys(user?.address as string),
);
},
},
);
}