Using @daml/ledger with React Class Components
- alex_mOP
I prefer React class-based components and so am migrating my app (currently based on daml-ui-template) to use class-based components. I hence cannot use hooks. i was wondering if there were any examples of the usage of
ledger.streamQuerysuch that it behaved similarly touseStreamQuery. Thanks!For example, from the
daml-ui-template…export default function Report() { const classes = useStyles(); const party = useParty(); const ledger = useLedger(); const assets = useStreamQuery(Asset).contracts; ... <TableBody> {assets.map((a, i) => ( <TableRow key={i} className={classes.tableRow}> ...How could I do this same thing without hooks, and with class components?
- drsk 1
Hi @alex_m,
I think you would have to write a class that maintains its own ledger object and also the state of the stream. Basically you would have to re-implement theuseStreamQueryfunction like here as a class component. In that piece of code you also see howledger.streamQueryis used.I hope that helps!
- alex_m
Looks promising! I’ll have a mess around and let you know.
- alex_m
I think I would in fact have to maintain a
Streamobject. The problem I am encountering is thatStreamis a generic type and the actual type signature of theStream(as returned from myledger.streamQuery(TransportationRecord)is very ugly. Something like:
Stream<TransportationRecord, undefined, "827c178267266bb80711c560783b5391b5a3a45035176e251689366b6ce2ee85:Records:TransportationRecord", readonly CreateEvent<TransportationRecord, undefined, "827c178267266bb80711c560783b5391b5a3a45035176e251689366b6ce2ee85:Records:TransportationRecord">[]>.
I’d rather not refer to it asany.I am thinking of setting
stream.on(...)stuff incomponentDidMountand then closing the stream oncomponountWillUnmount - alex_m 1
Solved my problem with:
const getStream = (ledger: Ledger) => ledger.streamQuery(TransportationRecord);
…
private stream: ReturnType<typeof getStream> | undefined = undefined; - drsk
Are you sure you need to maintain a
streamobject in your class? I would have expected that you maintain aQueryResultobject in your class and issue aledger.streamQueryon creation of the class instance. You then get astreamback where you register your callbacks to update theQueryResult. - alex_m
Yeah I think so. Wouldn’t you need to maintain a reference to the stream such that you can call
closeoncomponentWillUnmount?I would have expected that you maintain a
QueryResultobject in your class and issue aledger.streamQueryon creation of the class instance… So in the constructor? Can React components do fetchy things in a constructor?
- SamirTalwar
I think you want to hook into two of the React lifecycle methods, namely
componentDidMountandcomponentWillUnmount. Subscribe in the former, unsubscribe in the latter. - drsk
Not sure, otherwise you could have it as a method. I guess you need the
streamobject to properly close it.