React Native
Sync
Learn to sync when online.
Synchronization
Sending data saved offline to the server later is called synchronization. While the user is offline you write to a local queue; when they come online you send each item in the queue to the server in turn. This pattern prevents offline changes from being lost.
To start synchronization you use a NetInfo subscription: when the network state becomes online you call syncQueue(). This function takes each item in the queue, sends it to the server, removes it from the queue on success. On failure the item stays in the queue; it is retried on the next attempt. This pattern can be thought of like messages where 'send' has been pressed on paper but the network is waiting.
Triggering with a NetInfo subscription
You trigger synchronization when the network state changes. You use the NetInfo.addEventListener((state) => {{ if (state.isConnected) syncQueue(); }}) pattern. This subscription is called on every network change; when the connection comes the queue is synchronized.
You set up the subscription inside useEffect and remove it in cleanup. The subscription returns a function; this function is called unsubscribe and is called when the component unmounts. This pattern ensures the queue empties as soon as the user comes online. If the queue is full before the subscription is set up, a synchronization can also be tried as soon as the app opens.
Exercise Sync when the network comes
Complete the empty useEffect. Call const unsubscribe = NetInfo.addEventListener((state) => {{ if (state.isConnected) syncQueue(); }}). Clean up with return () => unsubscribe(). syncQueue is passed as a parameter. The second argument of useEffect should be [].
Show example solution
const unsubscribe = NetInfo.addEventListener((state) => {
if (state.isConnected) syncQueue();
});
return () => unsubscribe();
Test yourself
-
Write the synchronization function
async function ____() { /* send queue to server */ }
Show answer
async function syncQueue() { /* send queue to server */ }
-
When is synchronization started?
NetInfo.addEventListener((state) => { if (state.???) syncQueue(); })
- type === 'wifi'
- isInternetReachable === false
- details
- isConnected
Show answer
isConnected — Synchronization starts when isConnected becomes true.
-
Match each step to its purpose
- NetInfo.addEventListener
- Listens to network change
- syncQueue
- Sends the queue
- isConnected
- Connection state
- unsubscribe
- Removes the subscription
Next lesson: Conflict resolution