π Calling Sync from the Client
To call an API from the client, use the built-in apiRequest
function located at:
src/functions/serverRequest.ts
This function lets you trigger real-time behavior across all users β perfect for collaborative features, live dashboards, or synced state updates.
βΆοΈ Example: Calling the updateCounter Sync from the Client
// src/dashboard/page.tsx
import { syncRequest } from "src/functions/syncRequest";
export default function Dashboard() {
return (
<button onClick={() => {
syncRequest({
name: "updateDashboard",
data: {
product: 'shoes',
increase: true
}
})}
}>
Refresh All Clients
</button>
);
}
π§ syncRequest Parameters
Parameter
Type
Required
Description
name
string
β
The name of the Sync you want to call (e.g. "updateDashboard"
)
data
object
β
Optional data to pass to the API
π οΈ Example: Creating the updateDashboard_server file
import { PrismaClient } from '@prisma/client';
import { sessionLayout } from 'config';
type Functions = {
prisma: PrismaClient;
saveSession: (sessionId: string, data: any) => Promise<boolean>;
getSession: (sessionId: string) => Promise<any | null>;
deleteSession: (sessionId: string) => Promise<boolean>;
tryCatch: <T, P>(func: (values: P) => Promise<T> | T, params?: P) => Promise<[any, T | null]>;
[key: string]: any; // allows you to call functions you made yourself, autocomplete wont work for your own functions if you dont add them here
};
type SyncParams = {
data: Record<string, any>;
functions: Functions;
user: sessionLayout;
};
export default function removeCard({ data, user, functions }: SyncParams) {
if (user?.location?.pathName == '/test') {
return true;
}
}
π οΈ Example: Creating the updateDashboard_client file
type updateCounterProps = {
serverData: Record<string, any>;
clientData: Record<string, any>;
}
export default function updateCounter({ serverData, clientData }: updateCounterProps) {
console.log(serverData); // output: true
console.log(clientData); // output: { product: 'shoes', amount: 5 }
const counter = document.querySelector(`.${clientData.product}Counter span`) as HTMLSpanElement;
if (!counter) { return }
const newValue = (parseInt(counter.innerText) + (clientData.increase ? 1 : -1)).toString();
counter.innerText = newValue;
}
In the example above, we first check if the user is on the /test
route. If so, we trigger the client-side sync file to update a counter.
Last updated