StorageMutations

Storage Mutations

The Supabase Cache Helpers provide optimized mutation hooks for interacting with Supabase Storage using React Query or SWR. These hooks automatically revalidate related queries upon execution, ensuring a seamless cache update when uploading or removing files.


Mutation Configuration Options

import { UseMutationOptions } from '@tanstack/react-query';
 
type MutationConfig<TData, TError, TVariables> = Omit<
  UseMutationOptions<TData, TError, TVariables>,
  'mutationFn'
>;

These options are available for all mutations:

OptionTypeDescription
onMutate(variables: TVariables) => Promise<TData> | TDataCalled before the mutation function executes. Can return a context value used in onError or onSettled.
onError(error: TError, variables: TVariables, context?: unknown) => voidCalled if the mutation fails.
onSuccess(data: TData, variables: TVariables, context?: unknown) => voidCalled if the mutation succeeds.
onSettled(data?: TData, error?: TError, variables?: TVariables, context?: unknown) => voidCalled when mutation finishes, regardless of success or failure.
retryboolean | number | (failureCount: number, error: TError) => booleanNumber of retry attempts before failing.
retryDelay(failureCount: number, error: TError) => number | numberDelay between retries.
mutationKeyunknownA unique key to track the mutation state.
metaRecord<string, unknown>Additional metadata to associate with the mutation.

These options apply to:

  • useUpload
  • useRemoveDirectory
  • useRemoveFiles

For more details, refer to the React Query useMutation documentation.


Uploading Files

useUpload

Uploads a list of files to a specified directory in Supabase Storage.

Parameters:

useUpload(
  fileApi: StorageFileApi, // Supabase storage API instance
  config?: UploadFetcherConfig & UseMutationOptions<UploadFileResponse[], StorageError, UseUploadInput>
)

UseUploadInput Options:

type UseUploadInput = {
  files: FileList | (File | FileInput)[]; // Files to upload
  path?: string; // Optional storage path
};

Example Usage:

import { useUpload } from '@supabase-cache-helpers/storage-swr';
import { createClient } from '@supabase/supabase-js';
 
const client = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_ANON_KEY
);
 
function Page() {
  const { trigger: upload } = useUpload(
    client.storage.from('private_contact_files'),
    { buildFileName: ({ fileName, path }) => `${dirName}/${path}/${fileName}` }
  );
 
  function handleUpload(files) {
    upload({ files, path: 'user-123' });
  }
 
}

Removing a Directory

useRemoveDirectory

Removes all files inside a directory but does not delete subdirectories recursively.

Parameters:

useRemoveDirectory(
  fileApi: StorageFileApi, // Supabase storage API instance
  config?: UseMutationOptions<FileObject[], StorageError, string>
)

Example Usage:

import { useRemoveDirectory } from '@supabase-cache-helpers/storage-swr';
 
function Page() {}
  const { trigger: remove } = useRemoveDirectory(
    client.storage.from('uploads')
  );
 
  function handleRemove() {
    remove('user-123');
  }
}

Removing Specific Files

useRemoveFiles

Removes specific files in Supabase Storage by their paths.

Parameters:

useRemoveFiles(
  fileApi: StorageFileApi, // Supabase storage API instance
  config?: UseMutationOptions<FileObject[], StorageError, string[]>
)

Example Usage:

import { useRemoveFiles } from '@supabase-cache-helpers/storage-swr';
 
function Page() {
  const { trigger: remove } = useRemoveFiles(client.storage.from('uploads'));
 
  function handleRemove() {
    remove(['user-123/file1.png', 'user-123/file2.jpg']);
  }
}

Return Types for Mutations

HookReturn TypeDescription
useUploadUploadFileResponse[]List of uploaded files with paths and potential errors
useRemoveDirectoryFileObject[]List of removed files in the directory
useRemoveFilesFileObject[]List of removed files by path

UploadFileResponse Definition:

type UploadFileResponse = {
  path: string; // The uploaded file path
  error?: StorageError; // Error if applicable
};

StorageError Definition:

export interface StorageError {
  message: string; // Error message
  statusCode?: number; // HTTP status code (if applicable)
  error?: string; // Additional error info (if available)
}