Add Reflect to an Existing Project
These steps take about five minutes, and can be run with projects using frameworks likes React, Vue, or Svelte.
Install
npm install @rocicorp/reflect@latest
Join Discord
Join the Reflect Discord (opens in a new tab) so you'll be able to ask questions and get help.
Define Mutators
Mutators are how you make changes to data in Reflect. They are typically defined in their own file called mutators.ts
. Create this file anywhere in your project.
The first argument for each is always WriteTransaction
, and the second is up to you.
import type { WriteTransaction } from "@rocicorp/reflect";
export const mutators = {
increment,
};
async function increment(tx: WriteTransaction, delta: number) {
const value = (await tx.get<number>("count")) ?? 0;
await tx.set("count", value + delta);
}
JavaScript is supported too, just remove the types from the code snippets and change the file extension!
Build Your UI
Instantiate Reflect and register your mutators.
import { Reflect } from "@rocicorp/reflect/client";
import { mutators } from "./path/to/mutators";
const r = new Reflect({
roomID: "myRoom",
userID: "myUser",
mutators,
});
Call r.mutate.foo()
anywhere in your app to make changes to synced data, and render your UI reactively via subscriptions.
myButton.onclick = () => {
void r.mutate.increment(1);
};
r.subscribe(
(tx) => tx.get<number>("count"),
(count) => element.textContent = count,
);
Sync
Reflect runs your mutators on the server-side too. This is how it achieves server-authority (opens in a new tab).
To register your mutators with the server, create a new directory at the root of your project called /reflect-server
, and add an index.ts
file to it. This will be the entrypoint to your server code.
import { mutators } from "../path/to/mutators";
export default function makeOptions() {
return {
mutators,
};
}
Develop
Run the development Reflect server:
npx reflect dev
Update your Reflect constructor to talk to it:
const r = new Reflect({
server: "http://localhost:8080",
roomID: "myRoom",
mutators,
});
Then in a separate tab, run your app:
npm run dev
Now your app should sync changes to Reflect state live across tabs and browsers on the local machine.
Deploy
To sync between clients on different computers, deploy your server to reflect-server.net
:
npx reflect publish --app my-app
This will output the URL of your server on reflect-server.net. Update your Reflect constructor to talk to the production server instead:
const r = new Reflect({
server: "https://my-app-my-team.reflect-server.net",
roomID: "myRoom",
mutators,
Next Steps
You now know the essential principles of Reflect 🎉. Now it's time to learn more about how to use it in your app.
Have a question? Feel free to reach out to us.