Skip to content

Synapse React

Install dependencies:

Terminal window
npm install @filoz/synapse-react wagmi viem @tanstack/react-query

Requirements:

  • 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: FilecoinChain
calibration
,
const mainnet: FilecoinChain
mainnet
} 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>

@description Creates a HTTP transport that connects to a JSON-RPC API.

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: FilecoinChain
calibration
,
const mainnet: FilecoinChain
mainnet
],
transports: {
[mainnet.id]: HttpTransport<undefined, false>;
[calibration.id]: HttpTransport<undefined, false>;
}
transports
: {
[
const mainnet: FilecoinChain
mainnet
.
id: number

ID in number form

id
]:
http<undefined, false>(url?: string | undefined, config?: HttpTransportConfig<undefined, false> | undefined): HttpTransport<undefined, false>

@description Creates a HTTP transport that connects to a JSON-RPC API.

http
(),
[
const calibration: FilecoinChain
calibration
.
id: number

ID in number form

id
]:
http<undefined, false>(url?: string | undefined, config?: HttpTransportConfig<undefined, false> | undefined): HttpTransport<undefined, false>

@description Creates a HTTP transport that connects to a JSON-RPC API.

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
,
const QueryClientProvider: ({ client, children }: QueryClientProviderProps) => React.JSX.Element
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: QueryClient
queryClient
= new
new QueryClient(config?: QueryClientConfig): QueryClient
QueryClient
();
export default function
function App(): React.JSX.Element
App
() {
return (
<
function WagmiProvider(parameters: React.PropsWithChildren<WagmiProviderProps>): import("react").FunctionComponentElement<import("react").PropsWithChildren<import("wagmi").HydrateProps>>
WagmiProvider
config: Config
config
={
const config: Config
config
}>
<
const QueryClientProvider: ({ client, children }: QueryClientProviderProps) => React.JSX.Element
QueryClientProvider
client: QueryClient
client
={
const queryClient: QueryClient
queryClient
}>
<
const YourApp: () => React.JSX.Element
YourApp
/>
</
const QueryClientProvider: ({ client, children }: QueryClientProviderProps) => React.JSX.Element
QueryClientProvider
>
</
function WagmiProvider(parameters: React.PropsWithChildren<WagmiProviderProps>): import("react").FunctionComponentElement<import("react").PropsWithChildren<import("wagmi").HydrateProps>>
WagmiProvider
>
);
}

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): bigint

Multiplies a string representation of a number by a given exponent of base 10 (10exponent).

@example

import { parseUnits } from 'viem'

parseUnits('420', 9) // 420000000000n

parseUnits
} from "viem";
import {
function useAccount<config extends Config = Config>(parameters?: UseConnectionParameters<config>): UseConnectionReturnType<config>
useAccount
} from "wagmi";
const
const PaymentsExample: () => React.JSX.Element
PaymentsExample
= () => {
const {
const address: `0x${string}` | undefined
address
} =
useAccount<Config>(parameters?: UseConnectionParameters<Config> | undefined): UseConnectionReturnType<Config>
useAccount
();
const {
data: accounts.OutputType | undefined

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

data
:
const account: accounts.OutputType | undefined

The last successfully resolved data for the query.

account
,
const isLoading: boolean

Is true whenever the first fetch for a query is in-flight.

  • Is the same as isFetching && isPending.

isLoading
} =
function useAccountInfo(props?: UseAccountInfoProps): import("@tanstack/react-query").UseQueryResult<accounts.OutputType, Error>
useAccountInfo
(
const address: `0x${string}` | undefined
address
? {
address?: `0x${string}` | undefined
address
,
UseAccountInfoProps.watch?: boolean | undefined
watch
: true } : {
UseAccountInfoProps.watch?: boolean | undefined
watch
: 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) | undefined
onHash
: (
hash: string
hash
) =>
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

log
("Tx:",
hash: string
hash
),
});
if (!
const address: `0x${string}` | undefined
address
) 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

Is true whenever the first fetch for a query is in-flight.

  • Is the same as isFetching && isPending.

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 | undefined

The last successfully resolved data for the query.

account
?.
availableFunds: bigint
availableFunds
.
BigInt.toString(radix?: number): string

Returns a string representation of an object.

@param ― radix Specifies a radix for converting numeric values to strings.

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> | undefined
onClick
={() =>
const deposit: UseMutationResult<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown>
deposit
.
mutate: (variables: UseDepositAndApproveVariables, options?: MutateOptions<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown> | undefined) => void

The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options.

@param ― variables - The variables object to pass to the mutationFn.

@param ― options.onSuccess - This function will fire when the mutation is successful and will be passed the mutation's result.

@param ― options.onError - This function will fire if the mutation encounters an error and will be passed the error.

@param ― options.onSettled - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error.

@remarks ―

  • If you make multiple requests, onSuccess will fire only after the latest call you've made.
  • All the callback functions (onSuccess, onError, onSettled) are void functions, and the returned value will be ignored.

mutate
({
amount: bigint
amount
:
function parseUnits(value: string, decimals: number): bigint

Multiplies a string representation of a number by a given exponent of base 10 (10exponent).

@example

import { parseUnits } from 'viem'

parseUnits('420', 9) // 420000000000n

parseUnits
("1", 18) })}
React.ButtonHTMLAttributes<HTMLButtonElement>.disabled?: boolean | undefined
disabled
={
const deposit: UseMutationResult<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown>
deposit
.
isPending: boolean

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

isPending
}
>
{
const deposit: UseMutationResult<TransactionReceipt, Error, UseDepositAndApproveVariables, unknown>
deposit
.
isPending: boolean

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

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
>
);
};

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.

@version ― 16.8.0

@see ― https://react.dev/reference/react/useState

useState
} from "react";
import {
function useAccount<config extends Config = Config>(parameters?: UseConnectionParameters<config>): UseConnectionReturnType<config>
useAccount
} from "wagmi";
const
const StorageExample: () => React.JSX.Element
StorageExample
= () => {
const {
const address: `0x${string}` | undefined
address
} =
useAccount<Config>(parameters?: UseConnectionParameters<Config> | undefined): UseConnectionReturnType<Config>
useAccount
();
const {
data: getApprovedPDPProviders.OutputType | undefined

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

data
:
const providers: getApprovedPDPProviders.OutputType | undefined

The last successfully resolved data for the query.

providers
} =
function useProviders(props?: UseProvidersProps): import("@tanstack/react-query").UseQueryResult<getApprovedPDPProviders.OutputType, Error>
useProviders
();
const {
data: DataSetWithPieces[] | undefined

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

The last successfully resolved data for the query.

data
:
const dataSets: DataSetWithPieces[] | undefined

The last successfully resolved data for the query.

dataSets
} =
useDataSets<true>(props: UseDataSetsProps<true>): UseQueryResult<DataSetWithPieces[], Error>
useDataSets
(
const address: `0x${string}` | undefined
address
? {
UseDataSetsProps<true>.address?: `0x${string}` | undefined
address
} : {});
const [
const file: File | undefined
file
,
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.

@version ― 16.8.0

@see ― https://react.dev/reference/react/useState

useState
<
interface File

The File interface provides information about files and allows JavaScript in a web page to access their content.

MDN Reference

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 | null
source
: 'synapse',
callbacks?: Partial<CombinedCallbacks> | undefined
callbacks
:{
onPiecesAdded?: ((transaction: Hex, providerId: bigint, pieces: {
pieceCid: PieceCID;
}[]) => void) | undefined
onPiecesAdded
: (
hash: `0x${string}`
hash
) =>
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

log
("Tx:",
hash: `0x${string}`
hash
),
}
});
if (!
const address: `0x${string}` | undefined
address
) 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 | undefined

The last successfully resolved data for the query.

providers
?.
Array<PDPProvider>.length: number | undefined

Gets 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[] | undefined

The last successfully resolved data for the query.

dataSets
?.
Array<T>.length: number | undefined

Gets 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[] | undefined

The last successfully resolved data for the query.

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.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
ds: DataSetWithPieces
ds
) => (
<
React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div
React.Attributes.key?: React.Key | null | undefined
key
={
ds: DataSetWithPieces
ds
.
dataSetId: bigint
dataSetId
.
BigInt.toString(radix?: number): string

Returns a string representation of an object.

@param ― radix Specifies a radix for converting numeric values to strings.

toString
()}>
<
React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>
p
>Dataset {
ds: DataSetWithPieces
ds
.
dataSetId: bigint
dataSetId
.
BigInt.toString(radix?: number): string

Returns a string representation of an object.

@param ― radix Specifies a radix for converting numeric values to strings.

toString
()}: {
ds: DataSetWithPieces
ds
.
DataSetWithPieces.pieces: Piece[]
pieces
.
Array<T>.length: number

Gets 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 | undefined
type
="file"
React.InputHTMLAttributes<HTMLInputElement>.onChange?: React.ChangeEventHandler<HTMLInputElement, HTMLInputElement> | undefined
onChange
={(
e: React.ChangeEvent<HTMLInputElement, HTMLInputElement>
e
) =>
e: React.ChangeEvent<HTMLInputElement, HTMLInputElement>
e
.
React.ChangeEvent<HTMLInputElement, HTMLInputElement>.target: EventTarget & HTMLInputElement
target
.
HTMLInputElement.files: FileList | null

The HTMLInputElement.files property allows you to access the FileList selected with the element.

MDN Reference

files
&&
const setFile: (value: React.SetStateAction<File | undefined>) => void
setFile
(
e: React.ChangeEvent<HTMLInputElement, HTMLInputElement>
e
.
React.ChangeEvent<HTMLInputElement, HTMLInputElement>.target: EventTarget & HTMLInputElement
target
.
HTMLInputElement.files: FileList

The HTMLInputElement.files property allows you to access the FileList selected with the element.

MDN Reference

files
[0])
}
/>
<
React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
button
React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined
onClick
={() => {
if(!
const file: File | undefined
file
)return
const upload: UseMutationResult<UploadResult, Error, UseUploadVariables, unknown>
upload
.
mutate: (variables: UseUploadVariables, options?: MutateOptions<UploadResult, Error, UseUploadVariables, unknown> | undefined) => void

The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options.

@param ― variables - The variables object to pass to the mutationFn.

@param ― options.onSuccess - This function will fire when the mutation is successful and will be passed the mutation's result.

@param ― options.onError - This function will fire if the mutation encounters an error and will be passed the error.

@param ― options.onSettled - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error.

@remarks ―

  • If you make multiple requests, onSuccess will fire only after the latest call you've made.
  • All the callback functions (onSuccess, onError, onSettled) are void functions, and the returned value will be ignored.

mutate
({
UseUploadVariables.file: File
file
})
}}
React.ButtonHTMLAttributes<HTMLButtonElement>.disabled?: boolean | undefined
disabled
={
const upload: UseMutationResult<UploadResult, Error, UseUploadVariables, unknown>
upload
.
isPending: boolean

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

isPending
}
>
{
const upload: UseMutationResult<UploadResult, Error, UseUploadVariables, unknown>
upload
.
isPending: boolean

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

A boolean variable derived from status.

  • true if the mutation is currently executing.

isPending
? "Uploading..." : "Upload"}
</
React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
button
>
{
ds: DataSetWithPieces
ds
.
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.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
p: Piece
p
) => (
<
React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
div
React.Attributes.key?: React.Key | null | undefined
key
={
p: Piece
p
.
Piece.id: bigint
id
.
BigInt.toString(radix?: number): string

Returns a string representation of an object.

@param ― radix Specifies a radix for converting numeric values to strings.

toString
()}>
<
React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>
p
>Piece {
p: Piece
p
.
Piece.id: bigint
id
.
BigInt.toString(radix?: number): string

Returns a string representation of an object.

@param ― radix Specifies a radix for converting numeric values to strings.

toString
()}: {
p: Piece
p
.
Piece.cid: PieceCID
cid
.
CID<unknown, 85, 4113, 1>.toString(base?: MultibaseEncoder<string>): string

Returns 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: Piece
p
.
Piece.url: string | null
url
}</
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
>
);
};

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 {
(alias) interface PdpDataSet
import PdpDataSet
PdpDataSet
} from "@filoz/synapse-core/warm-storage";
import {
function useUploadPieces(props?: UseUploadPiecesProps): import("@tanstack/react-query").UseMutationResult<{
confirmations: {
txHash: `0x${string}`;
txStatus: "confirmed";
dataSetId: bigint;
pieceCount: number;
addMessageOk: true;
piecesAdded: true;
confirmedPieceIds: bigint[];
confirmedTxHash?: `0x${string}` | undefined;
}[];
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: PdpDataSet
dataSet
,
sessionKey: SessionKey<"Secp256k1"> | undefined
sessionKey
}: {
dataSet: PdpDataSet
dataSet
:
(alias) interface PdpDataSet
import PdpDataSet
PdpDataSet
;
sessionKey?: SessionKey<"Secp256k1"> | undefined
sessionKey
?:
interface SessionKey<KeyType extends SessionKeyType>
SessionKey
<"Secp256k1"> }) => {
const
const upload: UseMutationResult<{
confirmations: {
txHash: `0x${string}`;
txStatus: "confirmed";
dataSetId: bigint;
pieceCount: number;
addMessageOk: true;
piecesAdded: true;
confirmedPieceIds: bigint[];
confirmedTxHash?: `0x${string}` | undefined;
}[];
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: {
txHash: `0x${string}`;
txStatus: "confirmed";
dataSetId: bigint;
pieceCount: number;
addMessageOk: true;
piecesAdded: true;
confirmedPieceIds: bigint[];
confirmedTxHash?: `0x${string}` | undefined;
}[];
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 | undefined
sessionKey
,
UseUploadPiecesProps.onFileProgress?: ((progress: UploadPiecesFileProgress) => void) | undefined
onFileProgress
: ({
file: File
file
,
bytesUploaded: number
bytesUploaded
}) =>
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

log
(
file: File
file
.
File.name: string

The 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

name
,
bytesUploaded: number
bytesUploaded
),
UseUploadPiecesProps.onHash?: ((hash: string) => void) | undefined
onHash
: (
hash: string
hash
) =>
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

log
("Tx:",
hash: string
hash
),
});
return (
<
React.JSX.IntrinsicElements.input: React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
input
React.InputHTMLAttributes<HTMLInputElement>.type?: React.HTMLInputTypeAttribute | undefined
type
="file"
React.InputHTMLAttributes<HTMLInputElement>.multiple?: boolean | undefined
multiple
React.InputHTMLAttributes<HTMLInputElement>.onChange?: React.ChangeEventHandler<HTMLInputElement, HTMLInputElement> | undefined
onChange
={(
e: React.ChangeEvent<HTMLInputElement, HTMLInputElement>
e
) => {
const
const files: File[]
files
=
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<File>(iterable: Iterable<File> | ArrayLike<File>): File[] (+3 overloads)

Creates an array from an iterable object.

@param ― iterable An iterable object to convert to an array.

from
(
e: React.ChangeEvent<HTMLInputElement, HTMLInputElement>
e
.
React.ChangeEvent<HTMLInputElement, HTMLInputElement>.target: EventTarget & HTMLInputElement
target
.
HTMLInputElement.files: FileList | null

The HTMLInputElement.files property allows you to access the FileList selected with the element.

MDN Reference

files
?? []);
const upload: UseMutationResult<{
confirmations: {
txHash: `0x${string}`;
txStatus: "confirmed";
dataSetId: bigint;
pieceCount: number;
addMessageOk: true;
piecesAdded: true;
confirmedPieceIds: bigint[];
confirmedTxHash?: `0x${string}` | undefined;
}[];
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: {
txHash: `0x${string}`;
txStatus: "confirmed";
dataSetId: bigint;
pieceCount: number;
addMessageOk: true;
piecesAdded: true;
confirmedPieceIds: bigint[];
confirmedTxHash?: `0x${string}` | undefined;
}[];
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.

@param ― variables - The variables object to pass to the mutationFn.

@param ― options.onSuccess - This function will fire when the mutation is successful and will be passed the mutation's result.

@param ― options.onError - This function will fire if the mutation encounters an error and will be passed the error.

@param ― options.onSettled - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error.

@remarks ―

  • If you make multiple requests, onSuccess will fire only after the latest call you've made.
  • All the callback functions (onSuccess, onError, onSettled) are void functions, and the returned value will be ignored.

mutate
(
{
UseUploadPiecesVariables.dataSet: PdpDataSet
dataSet
,
UseUploadPiecesVariables.files: File[]
files
,
UseUploadPiecesVariables.metadata?: ((file: File) => MetadataObject) | undefined
metadata
: (
file: File
file
) => ({
name: string
name
:
file: File
file
.
File.name: string

The 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

name
}) },
{
MutateOptions<{ confirmations: { txHash: `0x${string}`; txStatus: "confirmed"; dataSetId: bigint; pieceCount: number; addMessageOk: true; piecesAdded: true; confirmedPieceIds: bigint[]; confirmedTxHash?: `0x${string}` | undefined; }[]; pieces: { file: File; pieceCid: PieceCID; pieceId: bigint | undefined; size: number; metadata: MetadataObject | undefined; }[]; failed: { file: File; error: Error; }[]; }, Error, UseUploadPiecesVariables, unknown>.onSuccess?: ((data: {
confirmations: {
txHash: `0x${string}`;
txStatus: "confirmed";
dataSetId: bigint;
pieceCount: number;
addMessageOk: true;
piecesAdded: true;
confirmedPieceIds: bigint[];
confirmedTxHash?: `0x${string}` | undefined;
}[];
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
onSuccess
: ({
pieces: {
file: File;
pieceCid: PieceCID;
pieceId: bigint | undefined;
size: number;
metadata: MetadataObject | undefined;
}[]
pieces
,
failed: {
file: File;
error: Error;
}[]
failed
}) => {
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

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.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

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 | undefined
pieceId
));
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

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.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
f: {
file: File;
error: Error;
}
f
) =>
f: {
file: File;
error: Error;
}
f
.
file: File
file
.
File.name: string

The 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

name
));
},
}
);
}}
/>
);
};

Check out the Synapse React Reference for all available query and mutation hooks.