Synapse React
Install dependencies:
npm install @filoz/synapse-react wagmi viem @tanstack/react-querypnpm add @filoz/synapse-react wagmi viem @tanstack/react-queryyarn add @filoz/synapse-react wagmi viem @tanstack/react-querybun add @filoz/synapse-react wagmi viem @tanstack/react-queryRequirements:
- React 18+, Wagmi 3.x, viem 2.x, TanStack Query 5.x
- Connected Web3 wallet
- Supported networks: Filecoin Mainnet, Filecoin Calibration
Wagmi config:
import { const calibration: FilecoinChaincalibration, const mainnet: FilecoinChainmainnet } from "@filoz/synapse-core/chains";
import { function createConfig<const chains extends readonly [Chain, ...Chain[]], transports extends Record<chains[number]["id"], Transport>, const connectorFns extends readonly CreateConnectorFn[]>(parameters: CreateConfigParameters<chains, transports, connectorFns>): Config<chains, transports, connectorFns>createConfig, function http<rpcSchema extends RpcSchema | undefined = undefined, raw extends boolean = false>(url?: string | undefined, config?: HttpTransportConfig<rpcSchema, raw>): HttpTransport<rpcSchema, raw>http } from "wagmi";
export const const wagmiConfig: Config<readonly [FilecoinChain, FilecoinChain], {
[mainnet.id]: HttpTransport<undefined, false>;
[calibration.id]: HttpTransport<undefined, false>;
}, readonly CreateConnectorFn[]>
wagmiConfig = createConfig<readonly [FilecoinChain, FilecoinChain], {
[mainnet.id]: HttpTransport<undefined, false>;
[calibration.id]: HttpTransport<undefined, false>;
}, readonly CreateConnectorFn[]>(parameters: CreateConfigParameters<readonly [FilecoinChain, FilecoinChain], {
[mainnet.id]: HttpTransport<undefined, false>;
[calibration.id]: HttpTransport<undefined, false>;
}, readonly CreateConnectorFn[]>): Config<readonly [FilecoinChain, FilecoinChain], {
[mainnet.id]: HttpTransport<undefined, false>;
[calibration.id]: HttpTransport<undefined, false>;
}, readonly CreateConnectorFn[]>
createConfig({
chains: readonly [FilecoinChain, FilecoinChain]chains: [const calibration: FilecoinChaincalibration, const mainnet: FilecoinChainmainnet],
transports: {
[mainnet.id]: HttpTransport<undefined, false>;
[calibration.id]: HttpTransport<undefined, false>;
}
transports: {
[const mainnet: FilecoinChainmainnet.id: numberID in number formid]: http<undefined, false>(url?: string | undefined, config?: HttpTransportConfig<undefined, false> | undefined): HttpTransport<undefined, false>http(),
[const calibration: FilecoinChaincalibration.id: numberID in number formid]: http<undefined, false>(url?: string | undefined, config?: HttpTransportConfig<undefined, false> | undefined): HttpTransport<undefined, false>http(),
},
});Provider setup:
Synapse React hooks work within Wagmi and TanStack Query providers. Set these up at the root of your app:
import { class QueryClient`QueryClient` is used to interact with a cache of queries and mutations. It owns a
`QueryCache` and a `MutationCache` (creating default ones if none are passed in) and holds
the default options that are applied to queries and mutations created through it.QueryClient, const QueryClientProvider: ({ client, children }: QueryClientProviderProps) => React.JSX.ElementUse the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to
focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
comes back online).QueryClientProvider } from "@tanstack/react-query";
import { function WagmiProvider(parameters: React.PropsWithChildren<WagmiProviderProps>): import("react").FunctionComponentElement<import("react").PropsWithChildren<import("wagmi").HydrateProps>>WagmiProvider } from "wagmi";
const const queryClient: QueryClientqueryClient = new new QueryClient(config?: QueryClientConfig): QueryClient`QueryClient` is used to interact with a cache of queries and mutations. It owns a
`QueryCache` and a `MutationCache` (creating default ones if none are passed in) and holds
the default options that are applied to queries and mutations created through it.QueryClient();
export default function function App(): React.JSX.ElementApp() {
return (
<function WagmiProvider(parameters: React.PropsWithChildren<WagmiProviderProps>): import("react").FunctionComponentElement<import("react").PropsWithChildren<import("wagmi").HydrateProps>>WagmiProvider config: Configconfig={const config: Configconfig}>
<const QueryClientProvider: ({ client, children }: QueryClientProviderProps) => React.JSX.ElementUse the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to
focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
comes back online).QueryClientProvider client: QueryClient**Required**
The `QueryClient` instance to provide.client={const queryClient: QueryClientqueryClient}>
<const YourApp: () => React.JSX.ElementYourApp />
</const QueryClientProvider: ({ client, children }: QueryClientProviderProps) => React.JSX.ElementUse the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to
focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
comes back online).QueryClientProvider>
</function WagmiProvider(parameters: React.PropsWithChildren<WagmiProviderProps>): import("react").FunctionComponentElement<import("react").PropsWithChildren<import("wagmi").HydrateProps>>WagmiProvider>
);
}Payments
Section titled “Payments”Query account info and make deposits using hooks:
import { function useAccountInfo(props?: UseAccountInfoProps): import("@tanstack/react-query").UseQueryResult<accounts.OutputType, Error>useAccountInfo, function useDepositAndApprove(props?: UseDepositAndApproveProps): import("@tanstack/react-query").UseMutationResult<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown>useDepositAndApprove } from "@filoz/synapse-react";
import { function parseUnits(value: string, decimals: number): bigintMultiplies a string representation of a number by a given exponent of base 10 (10exponent).
- Docs: https://viem.sh/docs/utilities/parseUnitsparseUnits } from "viem";
import { function useAccount<config extends Config = Config>(parameters?: UseConnectionParameters<config>): UseConnectionReturnType<config>https://wagmi.sh/react/api/hooks/useConnectionuseAccount } from "wagmi";
const const PaymentsExample: () => React.JSX.ElementPaymentsExample = () => {
const { const address: `0x${string}` | undefinedaddress } = useAccount<Config>(parameters?: UseConnectionParameters<Config> | undefined): UseConnectionReturnType<Config>https://wagmi.sh/react/api/hooks/useConnectionuseAccount();
const { data: accounts.OutputType | undefinedThe data from before the failed refetch, which is kept.
The last successfully resolved data for the query.
`undefined`, since the first fetch failed before any data was cached.
`undefined`, since the query has no data yet.
The `placeholderData` shown while the query has no data yet.data: const account: accounts.OutputType | undefinedThe data from before the failed refetch, which is kept.account, const isLoading: boolean`false`, since the first fetch isn't in flight.isLoading } = function useAccountInfo(props?: UseAccountInfoProps): import("@tanstack/react-query").UseQueryResult<accounts.OutputType, Error>useAccountInfo(
const address: `0x${string}` | undefinedaddress ? { address?: `0x${string}` | undefinedaddress, UseAccountInfoProps.watch?: boolean | undefinedwatch: true } : { UseAccountInfoProps.watch?: boolean | undefinedwatch: true }
);
const const deposit: UseMutationResult<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown>deposit = function useDepositAndApprove(props?: UseDepositAndApproveProps): import("@tanstack/react-query").UseMutationResult<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown>useDepositAndApprove({
UseDepositAndApproveProps.onHash?: ((hash: string) => void) | undefinedonHash: (hash: stringhash) => var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("Tx:", hash: stringhash),
});
if (!const address: `0x${string}` | undefinedaddress) return <React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>Connect wallet</React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>;
if (const isLoading: boolean`false`, since the first fetch isn't in flight.isLoading) return <React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>Loading...</React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>;
return (
<React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>
<React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>Available: {const account: accounts.OutputType | undefinedThe data from before the failed refetch, which is kept.account?.availableFunds: bigintavailableFunds.BigInt.toString(radix?: number): stringReturns a string representation of an object.toString()} USDFC</React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>
<React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>button
React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefinedonClick={() => const deposit: UseMutationResult<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown>deposit.mutate: (variables: UseDepositAndApproveVariables, options?: MutateOptions<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown> | undefined) => voidThe mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options.mutate({ amount: bigintamount: function parseUnits(value: string, decimals: number): bigintMultiplies a string representation of a number by a given exponent of base 10 (10exponent).
- Docs: https://viem.sh/docs/utilities/parseUnitsparseUnits("1", 18) })}
React.ButtonHTMLAttributes<HTMLButtonElement>.disabled?: boolean | undefineddisabled={const deposit: UseMutationResult<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown>deposit.isPending: boolean`false`, since the mutation isn't running.
`true`, since the mutation is running.isPending}
>
{const deposit: UseMutationResult<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown>deposit.isPending: boolean`false`, since the mutation isn't running.
`true`, since the mutation is running.isPending ? "Depositing..." : "Deposit 1 USDFC"}
</React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>button>
</React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>
);
};Storage
Section titled “Storage”Upload files and list data sets:
import { function useUpload(props: UseUploadProps): import("@tanstack/react-query").UseMutationResult<UploadResult, Error, UseUploadVariables, unknown>useUpload, function useDataSets<IncludePieces extends boolean = true>(props: UseDataSetsProps<IncludePieces>): import("@tanstack/react-query").UseQueryResult<UseDataSetsResult<IncludePieces>, Error>useDataSets, function useProviders(props?: UseProvidersProps): import("@tanstack/react-query").UseQueryResult<getApprovedPDPProviders.OutputType, Error>useProviders } from "@filoz/synapse-react";
import { function useState<S>(initialState: S | (() => S)): [S, React.Dispatch<React.SetStateAction<S>>] (+1 overload)Returns a stateful value, and a function to update it.useState } from "react";
import { function useAccount<config extends Config = Config>(parameters?: UseConnectionParameters<config>): UseConnectionReturnType<config>https://wagmi.sh/react/api/hooks/useConnectionuseAccount } from "wagmi";
const const StorageExample: () => React.JSX.ElementStorageExample = () => {
const { const address: `0x${string}` | undefinedaddress } = useAccount<Config>(parameters?: UseConnectionParameters<Config> | undefined): UseConnectionReturnType<Config>https://wagmi.sh/react/api/hooks/useConnectionuseAccount();
const { data: getApprovedPDPProviders.OutputType | undefinedThe data from before the failed refetch, which is kept.
The last successfully resolved data for the query.
`undefined`, since the first fetch failed before any data was cached.
`undefined`, since the query has no data yet.
The `placeholderData` shown while the query has no data yet.data: const providers: getApprovedPDPProviders.OutputType | undefinedThe data from before the failed refetch, which is kept.providers } = function useProviders(props?: UseProvidersProps): import("@tanstack/react-query").UseQueryResult<getApprovedPDPProviders.OutputType, Error>useProviders();
const { data: DataSetWithPieces[] | undefinedThe data from before the failed refetch, which is kept.
The last successfully resolved data for the query.
`undefined`, since the first fetch failed before any data was cached.
`undefined`, since the query has no data yet.
The `placeholderData` shown while the query has no data yet.data: const dataSets: DataSetWithPieces[] | undefinedThe data from before the failed refetch, which is kept.dataSets } = useDataSets<true>(props: UseDataSetsProps<true>): UseQueryResult<DataSetWithPieces[], Error>useDataSets(const address: `0x${string}` | undefinedaddress ? { UseDataSetsProps<true>.address?: `0x${string}` | undefinedaddress } : {});
const [const file: File | undefinedfile, const setFile: React.Dispatch<React.SetStateAction<File | undefined>>setFile] = useState<File>(): [File | undefined, React.Dispatch<React.SetStateAction<File | undefined>>] (+1 overload)Returns a stateful value, and a function to update it.useState<File>();
const const upload: UseMutationResult<UploadResult, Error, UseUploadVariables, unknown>upload = function useUpload(props: UseUploadProps): import("@tanstack/react-query").UseMutationResult<UploadResult, Error, UseUploadVariables, unknown>useUpload({
UseUploadProps.source: string | nullsource: 'synapse',
callbacks?: Partial<CombinedCallbacks> | undefinedcallbacks :{
onPiecesAdded?: ((transaction: Hex, providerId: bigint, pieces: {
pieceCid: PieceCID;
}[]) => void) | undefined
onPiecesAdded: (hash: `0x${string}`hash) => var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("Tx:", hash: `0x${string}`hash),
}
});
if (!const address: `0x${string}` | undefinedaddress) return <React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>Connect wallet</React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>;
return (
<React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>
<React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>Providers: {const providers: getApprovedPDPProviders.OutputType | undefinedThe data from before the failed refetch, which is kept.providers?.Array<PDPProvider>.length: number | undefinedGets or sets the length of the array. This is a number one higher than the highest index in the array.length ?? 0}</React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>
<React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>Data sets: {const dataSets: DataSetWithPieces[] | undefinedThe data from before the failed refetch, which is kept.dataSets?.Array<T>.length: number | undefinedGets or sets the length of the array. This is a number one higher than the highest index in the array.length ?? 0}</React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>
{const dataSets: DataSetWithPieces[] | undefinedThe data from before the failed refetch, which is kept.dataSets?.Array<DataSetWithPieces>.map<U>(callbackfn: (value: DataSetWithPieces, index: number, array: DataSetWithPieces[]) => U, thisArg?: any): U[]Calls a defined callback function on each element of an array, and returns an array that contains the results.map((ds: DataSetWithPiecesds) => (
<React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div React.Attributes.key?: React.Key | null | undefinedkey={ds: DataSetWithPiecesds.dataSetId: bigintdataSetId.BigInt.toString(radix?: number): stringReturns a string representation of an object.toString()}>
<React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>Dataset {ds: DataSetWithPiecesds.dataSetId: bigintdataSetId.BigInt.toString(radix?: number): stringReturns a string representation of an object.toString()}: {ds: DataSetWithPiecesds.DataSetWithPieces.pieces: Piece[]pieces.Array<T>.length: numberGets or sets the length of the array. This is a number one higher than the highest index in the array.length} pieces</React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>
<React.JSX.IntrinsicElements.input: React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>input
React.InputHTMLAttributes<HTMLInputElement>.type?: React.HTMLInputTypeAttribute | undefinedtype="file"
React.InputHTMLAttributes<HTMLInputElement>.onChange?: React.ChangeEventHandler<HTMLInputElement, HTMLInputElement> | undefinedonChange={(e: React.ChangeEvent<HTMLInputElement, HTMLInputElement>e) =>
e: React.ChangeEvent<HTMLInputElement, HTMLInputElement>e.React.ChangeEvent<HTMLInputElement, HTMLInputElement>.target: EventTarget & HTMLInputElementtarget.HTMLInputElement.files: FileList | nullThe **`HTMLInputElement.files`** property allows you to access the FileList selected with the <input type="file"> element.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/files)files && const setFile: (value: React.SetStateAction<File | undefined>) => voidsetFile(e: React.ChangeEvent<HTMLInputElement, HTMLInputElement>e.React.ChangeEvent<HTMLInputElement, HTMLInputElement>.target: EventTarget & HTMLInputElementtarget.HTMLInputElement.files: FileListThe **`HTMLInputElement.files`** property allows you to access the FileList selected with the <input type="file"> element.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/files)files[0])
}
/>
<React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>button
React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefinedonClick={() => {
if(!const file: File | undefinedfile)return
const upload: UseMutationResult<UploadResult, Error, UseUploadVariables, unknown>upload.mutate: (variables: UseUploadVariables, options?: MutateOptions<UploadResult, Error, UseUploadVariables, unknown> | undefined) => voidThe mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options.mutate({ UseUploadVariables.file: Filefile })
}}
React.ButtonHTMLAttributes<HTMLButtonElement>.disabled?: boolean | undefineddisabled={const upload: UseMutationResult<UploadResult, Error, UseUploadVariables, unknown>upload.isPending: boolean`false`, since the mutation isn't running.
`true`, since the mutation is running.isPending}
>
{const upload: UseMutationResult<UploadResult, Error, UseUploadVariables, unknown>upload.isPending: boolean`false`, since the mutation isn't running.
`true`, since the mutation is running.isPending ? "Uploading..." : "Upload"}
</React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>button>
{ds: DataSetWithPiecesds.DataSetWithPieces.pieces: Piece[]pieces.Array<Piece>.map<React.JSX.Element>(callbackfn: (value: Piece, index: number, array: Piece[]) => React.JSX.Element, thisArg?: any): React.JSX.Element[]Calls a defined callback function on each element of an array, and returns an array that contains the results.map((p: Piecep) => (
<React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div React.Attributes.key?: React.Key | null | undefinedkey={p: Piecep.Piece.id: bigintid.BigInt.toString(radix?: number): stringReturns a string representation of an object.toString()}>
<React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>Piece {p: Piecep.Piece.id: bigintid.BigInt.toString(radix?: number): stringReturns a string representation of an object.toString()}: {p: Piecep.Piece.cid: PieceCIDcid.CID<unknown, 85, 4113, 1>.toString(base?: MultibaseEncoder<string>): stringReturns a string representation of an object.toString()}</React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>
<React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>URL: {p: Piecep.Piece.url: string | nullurl}</React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>
</React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>
))}
</React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>
))}
</React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>
);
};Upload several files to one data set
Section titled “Upload several files to one data set”useUploadPieces uploads files to a data set you choose using synapse-core only. It streams each file to the provider, adds every parked piece in one signed add-pieces request, and returns the files that failed instead of rejecting the whole upload. Pass a session key to sign without wallet prompts.
import type { interface SessionKey<KeyType extends SessionKeyType>SessionKey } from "@filoz/synapse-core/session-key";
import type { PdpDataSet } from "@filoz/synapse-core/warm-storage";
import { function useUploadPieces(props?: UseUploadPiecesProps): import("@tanstack/react-query").UseMutationResult<{
confirmations: waitForAddPieces.OutputType[];
pieces: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}[];
failed: {
file: File;
error: Error;
}[];
}, Error, UseUploadPiecesVariables, unknown>
useUploadPieces } from "@filoz/synapse-react";
const const UploadFiles: ({ dataSet, sessionKey }: {
dataSet: PdpDataSet;
sessionKey?: SessionKey<"Secp256k1">;
}) => React.JSX.Element
UploadFiles = ({ dataSet: PdpDataSetdataSet, sessionKey: SessionKey<"Secp256k1"> | undefinedsessionKey }: { dataSet: PdpDataSetdataSet: PdpDataSet; sessionKey?: SessionKey<"Secp256k1"> | undefinedsessionKey?: interface SessionKey<KeyType extends SessionKeyType>SessionKey<"Secp256k1"> }) => {
const const upload: UseMutationResult<{
confirmations: waitForAddPieces.OutputType[];
pieces: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}[];
failed: {
file: File;
error: Error;
}[];
}, Error, UseUploadPiecesVariables, unknown>
upload = function useUploadPieces(props?: UseUploadPiecesProps): import("@tanstack/react-query").UseMutationResult<{
confirmations: waitForAddPieces.OutputType[];
pieces: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}[];
failed: {
file: File;
error: Error;
}[];
}, Error, UseUploadPiecesVariables, unknown>
useUploadPieces({
SessionKeySignerOptions.sessionKey?: SessionKey<"Secp256k1"> | null | undefinedsessionKey,
UseUploadPiecesProps.onFileProgress?: ((progress: UploadPiecesFileProgress) => void) | undefinedonFileProgress: ({ file: Filefile, bytesUploaded: numberbytesUploaded }) => var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(file: Filefile.File.name: stringThe **`name`** read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name)name, bytesUploaded: numberbytesUploaded),
UseUploadPiecesProps.onHash?: ((hash: string) => void) | undefinedonHash: (hash: stringhash) => var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("Tx:", hash: stringhash),
});
return (
<React.JSX.IntrinsicElements.input: React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>input
React.InputHTMLAttributes<HTMLInputElement>.type?: React.HTMLInputTypeAttribute | undefinedtype="file"
React.InputHTMLAttributes<HTMLInputElement>.multiple?: boolean | undefinedmultiple
React.InputHTMLAttributes<HTMLInputElement>.onChange?: React.ChangeEventHandler<HTMLInputElement, HTMLInputElement> | undefinedonChange={(e: React.ChangeEvent<HTMLInputElement, HTMLInputElement>e) => {
const const files: File[]files = var Array: ArrayConstructorArray.ArrayConstructor.from<File>(iterable: Iterable<File> | ArrayLike<File>): File[] (+3 overloads)Creates an array from an iterable object.from(e: React.ChangeEvent<HTMLInputElement, HTMLInputElement>e.React.ChangeEvent<HTMLInputElement, HTMLInputElement>.target: EventTarget & HTMLInputElementtarget.HTMLInputElement.files: FileList | nullThe **`HTMLInputElement.files`** property allows you to access the FileList selected with the <input type="file"> element.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/files)files ?? []);
const upload: UseMutationResult<{
confirmations: waitForAddPieces.OutputType[];
pieces: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}[];
failed: {
file: File;
error: Error;
}[];
}, Error, UseUploadPiecesVariables, unknown>
upload.mutate: (variables: UseUploadPiecesVariables, options?: MutateOptions<{
confirmations: waitForAddPieces.OutputType[];
pieces: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}[];
failed: {
file: File;
error: Error;
}[];
}, Error, UseUploadPiecesVariables, unknown> | undefined) => void
The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options.mutate(
{ UseUploadPiecesVariables.dataSet: PdpDataSetdataSet, UseUploadPiecesVariables.files: File[]files, UseUploadPiecesVariables.metadata?: ((file: File) => MetadataObject) | undefinedmetadata: (file: Filefile) => ({ name: stringname: file: Filefile.File.name: stringThe **`name`** read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name)name }) },
{
MutateOptions<{ confirmations: waitForAddPieces.OutputType[]; pieces: { file: File; pieceCid: PieceCID; pieceId: bigint | undefined; size: number; metadata: MetadataObject | undefined; }[]; failed: { file: File; error: Error; }[]; }, Error, UseUploadPiecesVariables, unknown>.onSuccess?: ((data: {
confirmations: waitForAddPieces.OutputType[];
pieces: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}[];
failed: {
file: File;
error: Error;
}[];
}, variables: UseUploadPiecesVariables, onMutateResult: unknown, context: MutationFunctionContext) => void) | undefined
Called when the mutation of this call succeeds, after the `onSuccess` of the mutation options.onSuccess: ({ pieces: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}[]
pieces, failed: {
file: File;
error: Error;
}[]
failed }) => {
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("Added", pieces: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}[]
pieces.Array<{ file: File; pieceCid: PieceCID; pieceId: bigint | undefined; size: number; metadata: MetadataObject | undefined; }>.map<bigint | undefined>(callbackfn: (value: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}, index: number, array: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}[]) => bigint | undefined, thisArg?: any): (bigint | undefined)[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.map((p: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}
p) => p: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}
p.pieceId: bigint | undefinedpieceId));
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("Retry", failed: {
file: File;
error: Error;
}[]
failed.Array<{ file: File; error: Error; }>.map<string>(callbackfn: (value: {
file: File;
error: Error;
}, index: number, array: {
file: File;
error: Error;
}[]) => string, thisArg?: any): string[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.map((f: {
file: File;
error: Error;
}
f) => f: {
file: File;
error: Error;
}
f.file: Filefile.File.name: stringThe **`name`** read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name)name));
},
}
);
}}
/>
);
};Check out the Synapse React Reference for all available query and mutation hooks.