txToaster
Showing transaction notifications with real-time progress updates
Last updated
Was this helpful?
Showing transaction notifications with real-time progress updates
Last updated
Was this helpful?
The Typink
generated project includes a built-in txToaster utility, making it easy to display transaction notifications with real-time progress updates and error details in case of failures. This helps keep users informed about the status of their transactions.
Basic usage
import { txToaster, TxToaster } from '@/utils/txToaster.tsx';
// Initialize a new toaster instance
const toaster: TxToaster = txToaster();
try {
// Sending transactions
// Update transaction progress
toaster.onTxProgress(...);
} catch (e) {
// Showing transaction errors
toaster.onTxError(e);
}
Let's put this on a real use-case to handle the setMessage
transaction from the greeter
contract:
// ...
import { useContract, useContractTx } from 'typink';
import { ContractId } from 'contracts/deployments.ts';
import { GreeterContractApi } from 'contracts/types/greeter';
const [message, setMessage] = useState('');
const { contract } = useContract<GreeterContractApi>(ContractId.GREETER);
const setMessageTx = useContractTx(contract, 'setMessage');
const doSetMessage = async () => {
if (!contract || !message) return;
try {
await setMessageTx.signAndSend({
args: [message],
callback: (progress) => {
const { status } = progress;
console.log(status);
if (status.type === 'BestChainBlockIncluded') {
setMessage(''); // Reset the message if the transaction is in block
}
// showing a toast notifying transaction status
},
});
} catch (e: any) {
console.error('Fail to make transaction:', e);
// showing a toast message
}
}
// ...
import { ISubmittableResult } from 'dedot/types';
type TxToaster = {
// Updates the toast based on transaction progress
onTxProgress: (progress: ISubmittableResult) => void;
// Updates the toast when a transaction error occurs
onTxError: (e: Error) => void;
};