Members
# CroquetContext
The react context to store the CroquetReactView
instance.
You can obtain the value by calling useContext(CroquetContext)
.
You can access useful values such as view, model, etc. from the value of this context.
Example:
const croquetView = useContext(CroquetContext);
const model = croquetView.model;
Methods
# CroquetRoot(sessionParams, showChildrenWithoutSessionopt, deferSessionopt)
Main wrapper component that manages a croquet sessions, enabling child elements to use the hooks described below. It takes the same parameters as Session.join except that it doesn't need a root View class, since croquet-react provides a suitable View class behind the scenes.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
sessionParams |
object | The session parameter object that is passed to Session.join.
If |
||
showChildrenWithoutSession |
boolean |
<optional> |
false | If true, children will be rendered even if there's no active session. |
deferSession |
boolean |
<optional> |
false | If true, the session creation will be deferred. |
function CounterApp() {
return (
<CroquetRoot
sessionParams={{
name: import.meta.env["VITE_CROQUET_NAME"],
password: import.meta.env["VITE_CROQUET_PASSWORD"],
appId: import.meta.env["VITE_CROQUET_APP_ID"],
apiKey: import.meta.env["VITE_CROQUET_API_KEY"],
model: CounterModel,
}}
>
<p>Your application here</p>
</CroquetRoot>
);
}
# useDetachCallback(callback)
Hook that sets up a callback for Croquet.View.detach(). The callback function is called when the root View is detached.
Name | Type | Description |
---|---|---|
callback |
function | The function to be called when the root View is detached |
function onDetached(): void {
// Callback logic here
}
useDetachCallback(onDetached);
# useIsJoined() → {boolean}
Returns whether the component is currently joined to a Croquet session.
True if joined to a Croquet session, false otherwise.
- Type
- boolean
const isJoined = useIsJoined();
if (isJoined) {
console.log("We are connected to a Croquet session");
}
# useJoinedViews() → {Object}
Returns information about the views currently joined to the Croquet session.
An object containing information about joined views.
views
- An array of unique identifiers for the joined views.viewCount
- The total number of views currently joined to the session.
- Type
- Object
const { views, viewCount } = useJoinedViews();
console.log(`There are ${viewCount} views joined to the session.`);
console.log('View IDs:', views.join(", "));
# useLeaveSession() → {function}
Hook that provides a function to leave the current Croquet session.
Calling the returned function does not affect the sessionParams
stored in CroquetRoot.
A function that, when called, will leave the current Croquet session.
- Type
- function
const leaveSession = useLeaveSession();
// Later in your code:
leaveSession();
# useModelById(id) → {M|null}
Hook that returns a reference to the Model instance with the given id. Keep in mind that even if the model data changes, React will not rerender the components that depend on its data. To achieve this behavior use useReactModelRoot or useModelSelector instead.
Name | Type | Description |
---|---|---|
id |
string | The id of the Model to retrieve. |
The model instance with the given id.
Returns null
if not currently joined to any session, or if an image with the given id was not found
- Type
- M | null
const userModel = useModelById<UserModel>('user-123');
if (userModel) {
console.log(userModel.name);
}
# useModelRoot() → {M|null}
Hook that returns a reference to the root Model instance of the current Croquet session. Keep in mind that even if the model data changes, React will not rerender the components that depend on its data. To achieve this behavior use useReactModelRoot or useModelSelector instead.
The root Model instance if available, or null if not.
- Type
- M | null
const rootModel = useModelRoot<RootModel>();
if (rootModel) {
console.log(rootModel.gameState);
}
# useModelSelector(selector) → {R|null}
Hook that selects and returns a specific part of the Model state. This hook updates state only when the selected data changes, using hashing to detect deep equality. This hook is a good alternative to useReactModelRoot, since it only re-renders when the subscribed part of the model changes.
The given selector
function should not return undefined
.
Name | Type | Description |
---|---|---|
selector |
function | A function that selects data from the model. The return type of this function will be used as the return type of the hook. |
The selected part of the Model state, or null if there is no current session.
- Type
- R | null
const playerScore = useModelSelector((model: GameModel) => model.playerScore);
if (playerScore !== null) {
console.log(`Current score: ${playerScore}`);
}
# usePublish(callback) → {function}
A hook for generating a function that publishes a view event.
The callback function provided takes one argument, data
, and returns an array
containing three elements that describe the event to be published:
- The scope to which the event is being emitted.
- The name of the event.
- The data attached to the event.
The data
argument corresponds to the value passed to the function returned by this hook.
Name | Type | Description |
---|---|---|
callback |
function | The callback function used to construct the event data. |
The function to be used to publish the event.
- Type
- function
type GrabData = { viewId: string, id: string };
const publishRelease = usePublish<GrabData>(
(data) => [model.id, 'release', data]
);
// Call the generated function to publish the 'release' event with specific data
publishRelease({ viewId: myViewId, id });
# useReactModelRoot() → {T|null}
A hook to obtain the reactive root model data.
This hook provides access to a React state representation of the root model, ensuring that components depending on it re-render when the model data changes.
Any changes to the model will trigger a re-render of components using this hook. Consider using useModelSelector for optimized performance.
An object mirroring the root model's interface, with the following characteristics:
- Contains all properties of the root model.
- Includes methods corresponding to each event the model is subscribed to. Calling such methods will publish the respective event.
- If a property name conflicts with a subscribed event name, the property value takes precedence.
- Returns
null
if there is no active Croquet session.
- Type
- T | null
// Using the hook
const model = useReactModelRoot<RootModel>();
if (model) {
// Accessing model properties
console.log(model.property1);
// Publishing events
model.event1();
model.event2(eventData);
} else {
console.log('No active Croquet session');
}
# useSession() → {CroquetSession.<CroquetReactView.<M>>|null}
Hook that returns the current Croquet session.
The current Croquet session, or null if not in a session.
- Type
- CroquetSession.<CroquetReactView.<M>> | null
const session = useSession<GameModel>();
if (session) {
console.log(`Connected to session: ${session.id}`);
}
# useSessionId() → {string|null}
Hook that returns the ID of the current Croquet session.
The ID of the current session, or null if not in a session.
- Type
- string | null
const sessionId = useSessionId();
console.log(sessionId ? `Current session: ${sessionId}` : 'Not in a session');
# useSessionParams() → {Object}
Hook that gives access to the sessionParams
object stored in the CroquetRoot state.
The sessionParams
object, which can be:
- If currently joined to a Croquet session: The parameters used in the active Session.join call.
- If not currently in a session, but previously joined: The parameters from the last joined session.
- If never joined a session: The initial parameters passed to CroquetRoot.
- Type
- Object
const sessionParams = useSessionParams();
console.log('Current session name:', sessionParams.name);
console.log('Application ID:', sessionParams.appId);
# useSetSession() → {function}
Hook that provides a function to join a new Session
The returned function:
- Accepts an object with override values for the
sessionParameters
object. - Applies these overrides to the existing
sessionParameters
in CroquetRoot state. - Automatically generates random strings for
name
andpassword
if they are null or undefined after applying overrides.
If the returned function is called when joined to a session, it leaves the previous session.
A function to join a new Croquet Session.
- Type
- function
const setSession = useSetSession();
// Later in your code:
setSession({name: 'new-name', password: 'password'});
# useSubscribe(scope, eventSpec, callback)
A hook to set up a subscription to a Croquet message.
Name | Type | Description |
---|---|---|
scope |
string | The scope in which we are subscribing to the event |
eventSpec |
string | The name of the event we are subscribing to |
callback |
function | The function to be called when the event is received |
function grabBall(data:GrabData): void {
// Callback logic here
}
useSubscribe<GrabData>(model.id, "grabbed", grabBall);
# useSyncedCallback(callback)
Hook that sets up a callback for Croquet.View.synced(). The callback function is called when a Croquet synced event occurs.
Name | Type | Description |
---|---|---|
callback |
function | The function to be called when a |
function onSynced(): void {
// Callback logic here
}
useSyncedCallback(onSynced);
# useUpdateCallback(callback)
Hook that sets up a callback for Croquet.View.update(). The callback function is called at each simulation cycle.
Name | Type | Description |
---|---|---|
callback |
function | The function to be called at each simulation cycle |
useUpdateCallback((update_time: number) => console.log(`Updated at ${update_time}!`));
# useView() → {CroquetReactView.<M>|null}
Hook that provides access to the current Croquet React View.
The current Croquet React View, or null if not available.
- Type
- CroquetReactView.<M> | null
const view = useView<GameView>();
if (view) {
console.log(`Current view ID: ${view.viewId}`);
}
# useViewId() → {string|null}
A hook to obtain the current viewId. Returns null
if not joined to any session
- Type
- string | null
const myViewId: string = useViewId();
# InCroquetSession()
Main wrapper component that starts and manages a croquet session, enabling child elements to use the hooks described above. It takes the same parameters as Session.join except that it doesn't need a root View class, since croquet-react provides a suitable View class behind the scenes.
- Deprecated:
- Use CroquetRoot instead.
function MyApp() {
return (
<InCroquetSession
apiKey="1_123abc",
appId="com.example.myapp"
name="mySession"
password="secret"
model={MyRootModel}
...
>
// child elements that use hooks go here...
<MyComponent/>
</InCroquetSession>
);
}
# createCroquetSession()
When Croquet is used in a component that is a part of a bigger application, it is sometimes better to establish the Croquet session instance outside,and then pass it in to the Croquet-powered part.
- Deprecated:
- Use CroquetRoot instead.
- the Croquet session object.
const [croquetSession, setCroquetSession] = useState(null);
const calledOnce = useRef(false);
useEffect(() => {
if (!calledOnce.current) {
calledOnce.current = true;
const sessionParams = {
name: projectId,
apiKey: import.meta.env.VITE_CROQUET_API_KEY,
tps: 0.5,
appId: import.meta.env.VITE_CROQUET_APP_ID,
password: "abc",
model: MyCroquetModel,
eventRateLimit: import.meta.env.EVENT_RATE_LIMIT || 60,
};
createCroquetSession(sessionParams as any).then((session) => {
console.log(`session created`);
setCroquetSession(session);
});
}
}, [...]);
return (
<CroquetRoot session={croquetSession}>
<MyCroquetComponent/>
</CroquetRoot>
);
# useConnectedViews()
- Deprecated:
- since version 2.2.0. Alias for useJoinedViews. Use that hook instead.
# useCroquetSession()
- Deprecated:
- since version 2.2.0. Alias for useSession. Use that hook instead.
# useCroquetView()
- Deprecated:
- since version 2.2.0. Alias for useView. Use that hook instead.