Building a Seamless Offline Experience with WatermelonDB and AdonisJs
As we continue to explore the world of offline-capable apps, we’re going to take our previous React Native weight tracking app to the next level by integrating WatermelonDB’s sync feature with an AdonisJs server-side API application. This powerful combination will enable our app to seamlessly synchronize data between the client and server, even when offline.
Laying the Foundation
To get started, we’ll use the code from our previous post as a starting point. Clone the repository and check out the v1
branch. Once you have the code and its dependencies installed, launch the app on your platform of choice using either your device or an emulator.
Syncing Data with WatermelonDB
WatermelonDB provides an out-of-the-box sync feature that allows us to keep our data in sync across devices. We’ll create a sync.ts
file inside the data
folder and define three essential functions: synchronize
, pullChanges
, and pushChanges
. These functions will enable our app to communicate with the server API and exchange data.
Generating the AdonisJs API App
Using AdonisJs, we’ll generate a new API app by running yarn create adonis-ts-app api
. This will create a directory named api
with the necessary boilerplate code. We’ll then set up our database using MySQL and Lucid as the ORM.
Defining the Data Structure
To replicate the data structure from WatermelonDB, we’ll create a migration to define the weights
table in our MySQL database. We’ll also generate a Weight
model to interact with the data.
Building the REST API Endpoints
Next, we’ll create two REST API endpoints: one for GET requests to pull data from the server and another for POST requests to push data to the server. These endpoints will be triggered by the pullChanges
and pushChanges
functions from WatermelonDB.
Implementing the Sync Indicator UX
To provide a seamless user experience, we’ll create a sync indicator component that displays the syncing status to the user. This component will trigger the sync function when the app is opened and display a success or failure message accordingly.
Testing the Offline Sync Behavior
To test our offline sync behavior, we’ll simulate an offline scenario by turning on airplane mode, adding a new weight entry, and then reconnecting to the internet. We should see the sync indicator display a success message, and the new entry should be visible in the server database.
Where to Go from Here
Congratulations! You now have a weight tracking app with full offline support. However, there’s still room for improvement. Consider adding features like detailed error viewers, data export and import capabilities, and partial sync failure handling to take your app to the next level.
Start Monitoring Your React Native Apps with LogRocket
LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps. Try LogRocket for free today!