The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: adds react query example templates
Alaister Younge59c04adb161
diff --git a/studio/data/__templates/README.md b/studio/data/__templates/README.mdnew file mode 100644index 00000000000..70febd8df66--- /dev/null+++ b/studio/data/__templates/README.md@@ -0,0 +1,49 @@+# Templates for Tanstack Query queries & mutations++## Usage++1. Duplicate the files in the \_\_templates directory you need depending on your use case.+2. Rename the files to match your resource name.+3. Update the `resource` variables to match your resource name. Usually find and replace works great here if you use case sensitive search (`resource` then `Resource`)+4. Implement your `queryFn` function.++Referencing the other files in the `data` directory is a good way to see how to use the library.++### SQL queries and mutations++The dashboard often needs to query the users database directly. There are already some reusable hooks for this in `data/sql`. Reference the `data/fdw` directory for an example of how to use them.++Note that the query key of the `useExecuteSqlQuery` hook will be automatically filled with an md5 hash of the SQL query, unless you provide a name for the query.++## Files++### `resources-query.ts`++For queries that return a list of results.++> :warning: Should only be used for simple lists, as it does not include any pagination. `useInfiniteQuery` should be used instead.++### `resource-query.ts`++For getting a single item based on parameter(s). `id` is used in this example but can be updated to whatever is needed.++### `resource-update.ts`++For updating a resource. This can easily be adapted to work for create, delete, or any verb that is needed. You may need to modify the `invalidateQueries` section depending on your use case. For example removing:++```ts+queryClient.invalidateQueries(resourceKeys.resource(projectRef, id))+```++if you are creating a new resource.++### `keys.ts`++Standardized keys for use with `useQuery` and `invalidateQueries`. This is not required but is a good way to keep things consistent.++## Learning Resources++- [Tanstack Query Docs](https://tanstack.com/query/v4/docs/react/overview)+- [TkDodo's Blog Posts](https://tanstack.com/query/v4/docs/react/community/tkdodos-blog)++The blog posts in particular are very helpful for learning best practices and how to use the library effectively.diff --git a/studio/data/__templates/keys.ts b/studio/data/__templates/keys.tsnew file mode 100644index 00000000000..fa363702862--- /dev/null+++ b/studio/data/__templates/keys.ts@@ -0,0 +1,5 @@+export const resourceKeys = {+ list: (projectRef: string | undefined) => ['projects', projectRef, 'resources'] as const,+ resource: (projectRef: string | undefined, id: string | undefined) =>+ ['projects', projectRef, 'resources', id] as const,+}diff --git a/studio/data/__templates/resource-query.ts b/studio/data/__templates/resource-query.tsnew file mode 100644index 00000000000..4c91e063b3a--- /dev/null+++ b/studio/data/__templates/resource-query.ts@@ -0,0 +1,60 @@+import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'+import { get } from 'lib/common/fetch'+import { API_URL } from 'lib/constants'+import { useCallback } from 'react'+import { resourceKeys } from './keys'++export type ResourceVariables = {+ projectRef?: string+ id?: string+}++export type ResourceResponse = {+ id: string+}++export async function getResource({ projectRef, id }: ResourceVariables, signal?: AbortSignal) {+ if (!projectRef) {+ throw new Error('projectRef is required')+ }+ if (!id) {+ throw new Error('id is required')+ }++ const response = await get(`${API_URL}/projects/${projectRef}/resources/${id}`, {+ signal,+ })+ if (response.error) {+ throw response.error+ }++ return response as ResourceResponse+}++export type ResourceData = Awaited<ReturnType<typeof getResource>>+export type ResourceError = unknown++export const useResourceQuery = <TData = ResourceData>(+ { projectRef, id }: ResourceVariables,+ { enabled = true, ...options }: UseQueryOptions<ResourceData, ResourceError, TData> = {}+) =>+ useQuery<ResourceData, ResourceError, TData>(+ resourceKeys.resource(projectRef, id),+ ({ signal }) => getResource({ projectRef, id }, signal),+ {+ enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined',+ ...options,+ }+ )++export const useResourcePrefetch = ({ projectRef, id }: ResourceVariables) => {+ const client = useQueryClient()++ return useCallback(() => {+ if (projectRef && id) {+ client.prefetchQuery(resourceKeys.resource(projectRef, id), ({ signal }) =>+ getResource({ projectRef, id }, signal)+ )+ }+ }, [projectRef])+}diff --git a/studio/data/__templates/resource-update.ts b/studio/data/__templates/resource-update.tsnew file mode 100644index 00000000000..b1d6d2ba099--- /dev/null+++ b/studio/data/__templates/resource-update.ts@@ -0,0 +1,50 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { patch } from 'lib/common/fetch'+import { API_URL } from 'lib/constants'+import { resourceKeys } from './keys'++export type ResourceUpdateVariables = {+ projectRef: string+ id: string+ updatedParam: string+}++export async function updateResource({ projectRef, id, updatedParam }: ResourceUpdateVariables) {+ const response = await patch(`${API_URL}/projects/${projectRef}/resources/${id}`, {+ updated_param: updatedParam,+ })+ if (response.error) {+ throw response.error+ }++ return response+}++type ResourceUpdateData = Awaited<ReturnType<typeof updateResource>>++export const useResourceUpdateMutation = ({+ onSuccess,+ ...options+}: Omit<+ UseMutationOptions<ResourceUpdateData, unknown, ResourceUpdateVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<ResourceUpdateData, unknown, ResourceUpdateVariables>(+ (vars) => updateResource(vars),+ {+ async onSuccess(data, variables, context) {+ const { projectRef, id } = variables++ await Promise.all([+ queryClient.invalidateQueries(resourceKeys.list(projectRef)),+ queryClient.invalidateQueries(resourceKeys.resource(projectRef, id)),+ ])++ await onSuccess?.(data, variables, context)+ },+ ...options,+ }+ )+}diff --git a/studio/data/__templates/resources-query.ts b/studio/data/__templates/resources-query.tsnew file mode 100644index 00000000000..9ff95df37f7--- /dev/null+++ b/studio/data/__templates/resources-query.ts@@ -0,0 +1,53 @@+import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'+import { get } from 'lib/common/fetch'+import { API_URL } from 'lib/constants'+import { useCallback } from 'react'+import { resourceKeys } from './keys'++export type ResourcesVariables = {+ projectRef?: string+}++export type ResourcesResponse = {+ id: string+}++export async function getResources({ projectRef }: ResourcesVariables, signal?: AbortSignal) {+ if (!projectRef) {+ throw new Error('projectRef is required')+ }++ const response = await get(`${API_URL}/projects/${projectRef}/resources`, {+ signal,+ })+ if (response.error) {+ throw response.error+ }++ return response as ResourcesResponse[]+}++export type ResourcesData = Awaited<ReturnType<typeof getResources>>+export type ResourcesError = unknown++export const useResourcesQuery = <TData = ResourcesData>(+ { projectRef }: ResourcesVariables,+ { enabled = true, ...options }: UseQueryOptions<ResourcesData, ResourcesError, TData> = {}+) =>+ useQuery<ResourcesData, ResourcesError, TData>(+ resourceKeys.list(projectRef),+ ({ signal }) => getResources({ projectRef }, signal),+ { enabled: enabled && typeof projectRef !== 'undefined', ...options }+ )++export const useResourcesPrefetch = ({ projectRef }: ResourcesVariables) => {+ const client = useQueryClient()++ return useCallback(() => {+ if (projectRef) {+ client.prefetchQuery(resourceKeys.list(projectRef), ({ signal }) =>+ getResources({ projectRef }, signal)+ )+ }+ }, [projectRef])+}