Using SyncState without React
Using SyncState without React is possible and not very different from its usage with React. The main reason behind this is store.useDoc
function with very similar API as useDoc
hook for React.
But there is a difference. Your React component subscribes to changes at the path passed to useDoc
hook, while store.useDoc
only returns the state and setter function without the subscription. You can subscribe to state changes using observe(path, listener, depth)
Let's see an example
// Create store
const initialDoc = { todos: [] };
const store = createDocStore(initialDoc);
// Define actions
function addTodo(setTodos, todoItem) {
setTodos((todos) => {
todos.push(todoItem);
});
}
// Fetching and updating state
const [todos, setTodos] = store.useDoc("/todos");
addTodo(setTodos, { caption: "hello", done: false });
// Subscribe to state changes
const dispose = store.observe(
"/todos",
(todos, change) => {
console.log("todos has been updated");
console.log("Updated todos: ", todos);
},
1
);