useComments
A React key that goes up whenever a shopper posts a comment, so Salla's comments component reloads without a page refresh.
import { useComments, UseCommentsResult } from '@salla.sa/twilight-theme-engine/hooks/useComments';In plain words
Salla's comments list is a ready-made web component that does not refresh itself after someone posts. Put key={commentsKey} on it. When a comment is added, the hook increases that number, and React replaces the component with a fresh one that loads the comments again.
A key is a special prop React uses to tell elements apart: when it changes, React throws the old element away and mounts a new one.
Signature
function useComments(): UseCommentsResult
interface UseCommentsResult {
commentsKey: number; // starts at 0
refresh: () => void; // commentsKey + 1
}Try it live
import { SallaComments } from '@salla.sa/twilight-components-react/comments';
import { useComments } from '@salla.sa/twilight-theme-engine/hooks/useComments';
export function ProductComments({ productId }: { productId: number }) {
const { commentsKey } = useComments();
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- the engine passes the type the same way
return <SallaComments key={commentsKey} itemId={productId} type={'product' as any} />;
}
Example
import { SallaComments } from '@salla.sa/twilight-components-react/comments';
import { useComments } from '@salla.sa/twilight-theme-engine/hooks/useComments';
export function ProductComments({ productId }: { productId: number }) {
const { commentsKey } = useComments();
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- the engine passes the type the same way
return <SallaComments key={commentsKey} itemId={productId} type={'product' as any} />;
}
How it behaves
In an effect it subscribes with
Salla.comment.event.onAddedand unsubscribes withSalla.event.off('comment::added', handler).refresh()only increases the key; the comments component reloads because it is mounted again.The engine's
ProductPage,BlogSinglePage,PageSingleandTestimonialsPageall key their comments component this way.
Gotchas
It loads no comments itself. Without a component keyed on
commentsKey, it changes nothing on the page.A new key resets everything inside the comments component: its pagination, scroll position and any half-written reply.
The subscription needs
window.Salla.comment.eventwhen the effect runs. If the SDK is not there yet, new comments never bump the key.
Related
Source and docs
- Engine source:
packages/theme-engine/src/hooks/useComments.ts