Realtime Updates
To enable real-time updates, we’ll modify the useEffect
hook to use liveQuery
.
Code Explanation
- We use the
liveQuery
method fromtaskRepo
to subscribe to real-time updates for tasks. - The
subscribe
method listens for changes and updates the state withinfo.applyChanges
. - We return the result of
subscribe
from theuseEffect
hook, so that once the component unmounts, it will automatically unsubscribe from the updates.
Try It Out
Try making changes as user-a
in the preview and see the effect on user-b
. You’ll notice that changes made by one user are immediately reflected for the other user without the need to reload the page.
Implementation Details
- The real-time updates implementation is adapter-based. The default implementation used for development and up to several hundreds of users uses Server-Sent Events (SSE).
- There are multiple adapters available to use other technologies, including third-party providers such as Ably.
Simplifying State Management
Now that we can rely on liveQuery
, we no longer need to manually update the tasks
state, as liveQuery
will handle that for us.
Code Explanation
- In the
addTask
,setCompleted
, anddeleteTask
functions, we removed the lines that manually update thetasks
state. - With
liveQuery
, the state updates automatically whenever there are changes to the tasks, simplifying our state management.
Files
Preparing Environment
- Installing dependencies
- Starting http server