useToast
Another name for toast: the same object, not a React hook, so there is nothing to call at the top of a component.
import { useToast } from '@salla.sa/twilight-theme-engine/components/toast';In plain words
useToast looks like a hook (a function whose name starts with use, called at the top of a component), but it is not one. It is exactly the same object as toast, exported under a second name.
So there is no const toast = useToast() step: call its methods directly, useToast.success('Saved'), from a click handler. Importing it as toast instead reads better and avoids the confusion.
Signature
const useToast: ToastFn // the very same object as toast // useToast === toast → true
Try it live
useToast === toast is true
import { toast } from '@salla.sa/twilight-theme-engine/components/toast';
export function ApplyCouponButton() {
// Prefer the name toast: calling useToast(…) inside a handler trips the hooks lint rule.
return (
<button type="button" className="btn btn--primary" onClick={() => toast.info('Your coupon was applied')}>
Apply
</button>
);
}
Example
import { useToast } from '@salla.sa/twilight-theme-engine/components/toast';
export function ApplyCouponButton({ apply }: { apply: () => Promise<void> }) {
const onClick = async () => {
try {
await apply();
useToast.success('Coupon applied'); // a method call, not a hook call
} catch {
useToast.error('This coupon is not valid');
}
};
return (
<button type="button" className="btn btn--primary" onClick={onClick}>
Apply
</button>
);
}
How it behaves
The source is
export const useToast: ToastFn = Object.assign(…)followed byexport { useToast as toast }(useToast.ts). It uses no React API, so the rules of hooks do not apply to it.Everything on the toast page applies, including the broken
update().
Gotchas
docs/18-hooks-api.md shows
const toast = useToast();thentoast.promise(…). TypeScript rejects the call (the title is required). In plain JavaScript it shows an empty toast on every render and returns a number (the new toast's id), sotoast.promisethrowsTypeError: toast.promise is not a function. Call the methods on the import itself.Calling it directly,
useToast('Saved'), inside an event handler fails ESLint'sreact-hooks/rules-of-hooksrule ("React Hook useToast cannot be called inside a callback") in any theme that enables it, as the twilight-platform repository does, only because of the name. Method calls likeuseToast.success('Saved')pass, and so does anything on thetoastimport.