[SOLVED] React: how to execute code after component gets loaded?

I’m trying to make a table sortable. There’s this popular library. It may work without PureScript code, but in my case the table is created dynamically, so I need to call makeSortable over the table via FFI.

Now, I am not sure how to call any Effect over the table as it gets created. The code obviously has to be encapsulated inside a “table” component. So, like, I’d have this:

tableSortable :: Array JSX -> React.Component Unit
tableSortable children =
  React.component "tableSortable" \_ -> React.do
    pure $ R.table_ children

and somewhere inside I need to either call makeSortable or hook it up to an event. I presume, the HTML doesn’t exist till the pure $ … part was executed, which implies makeSortable has to be hooked up to an event.

I looked up if there’s some onRender or onLoad, but I don’t see any, so I am not sure how to implement this.

1 Like

Okay, figured it out. There’re useEffect and useEffectOnce that are executed once the component loaded. So the solution is adding a ref to the table, and then executing makeSortable over the ref inside useEffectOnce.

Example with the helpers documented here:

type NodeRef = Ref (Nullable Node)

newNodeRef :: React.Hook (React.UseRef (Nullable Node)) NodeRef
newNodeRef = React.useRef null

applyToReactRef :: NodeRef -> (Node -> Effect Unit) -> Effect Unit
applyToReactRef mbRef f = readRefMaybe mbRef >>= case _ of
  Nothing -> log "Error: null node"
  Just ref -> f ref

tableSortable :: React.Component (Array JSX)
tableSortable = React.component "tableSortable" \children -> React.do
  tblRef <- newNodeRef
  useEffectOnce do
    applyToReactRef tblRef makeSortable
    pure mempty
  pure $ R.table { ref: tblRef, children }
1 Like