Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Created September 23, 2021 16:34
Show Gist options
  • Save steveruizok/73f1bb350de591f2f38fea59d36e5ac0 to your computer and use it in GitHub Desktop.
Save steveruizok/73f1bb350de591f2f38fea59d36e5ac0 to your computer and use it in GitHub Desktop.
Croquet.io React Bindings (requires @croquet/react and @croquet/croquet)
import * as React from "react"
import { Model } from "@croquet/croquet"
import { CroquetContext } from "@croquet/react"
/**
* A callback that publishes the returned data to the current view's model.
* @param eventName The name of the event to be published.
* @param fn A function that returns the data to be published.
* @param deps (optional) An array of dependencies for the callback.
*/
export function usePublishCallback<K>(
eventName: string,
fn: (...args: any[]) => Omit<K, "viewId">,
deps = []
) {
const context = React.useContext(CroquetContext)!
const model = (context as any).model as Model
const { view } = context
return React.useCallback(
(...args) => {
view.publish(model.id, eventName, {
viewId: view.viewId,
...fn(...args),
})
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[view, ...deps]
)
}
import * as React from "react"
import { Model } from "@croquet/croquet"
import { CroquetContext } from "@croquet/react"
/**
* A callback that subscribes to an event and runs a callback when the event is published.
* @param eventName The name of the event to be subscribed to.
* @param fn A function that runs when the event is published.
* @param deps (optional) An array of dependencies for the callback.
*/
export function useSubscribeCallback<K>(
eventName: string,
fn: (data: K) => void,
deps = []
) {
const context = React.useContext(CroquetContext)!
const model = (context as any).model as Model
const { view } = context
React.useEffect(
() => {
// Subscriptions here...
view.subscribe(model.id, eventName, fn)
return () => view.unsubscribe(model.id, eventName)
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[view, ...deps]
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment