Replicache JS SDK
Offline-First for Every Application
👋 Quickstart
This tutorial walks through creating a basic offline-first todo app with Replicache. If you have any problems or questions, please join us on Slack. We'd be happy to help.
You can also skip to the end and check out the full working version of this sample.
Note: This document assumes you already know what Replicache is, why you might need it, and broadly how it works. If that's not true check out the design document for a detailed deep-dive.
🏃♂️ Install
npm install replicache
🚴🏿♀️ Instantiate
Replicache ships with both ES6 and CommonJS modules. For simplicity, these examples use ES6.
<script type="module">
import Replicache from './node_modules/replicache/out/mod.js';
var rep = new Replicache({
diffServerURL: 'https://serve.replicache.dev/pull',
diffServerAuth: '1',
batchURL: 'https://replicache-sample-todo.now.sh/serve/replicache-batch',
dataLayerAuth: '2',
});
</script>
🚗 Render UI
Use subscribe()
to open standing queries. Replicache fires onData
whenever the result of the query changes, either because of local changes or sync.
rep.subscribe(
async tx => {
return await toArray(tx.scan({prefix: '/todo/'}));
},
{
onData: result => {
const toggle = complete =>
html`<td><input type="checkbox" .checked=${complete} /></td>`;
const title = text => html`<td>${text}</td>`;
const row = todo =>
html`<tr>
${toggle(todo.complete)}${title(todo.text)}
</tr>`;
render(
html`<table>
${result.map(row)}
</table>`,
document.body,
);
},
},
);
🏎 Mutate Data
Register client-side mutators using register()
.
Mutators run completely locally, without waiting on the server — online, offline, whatever! A record of the mutation is queued and sent to your service's batch endpoint when possible.
Replicache also invokes mutators itself, during sync, to replay unacknowledged changes on top of newly received server state.
const updateTodo = rep.register('updateTodo', async (tx, {id, complete}) => {
const key = `/todo/${id}`;
const todo = await tx.get(key);
todo.complete = complete;
await tx.put(key, todo);
});
const handleCheckbox = async (id, e) => {
await updateTodo({id, complete: e.srcElement.checked});
};
🛫 Tips
🚀 Next Steps
That's it! You've built a fully-functioning offline-first todo app against our sample backend. What will you do next?