Sync
- React Native course
- Advanced
- Lesson 33/83
- 5 min
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.
Practice 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 [].
Starter code
import React from 'react';
import NetInfo from '@react-native-community/netinfo';
export function useSyncOnOnline(syncQueue) {
React.useEffect(() => {
// sync when the network comes and return cleanup
}, []);
}Sample solution
const unsubscribe = NetInfo.addEventListener((state) => {
if (state.isConnected) syncQueue();
});
return () => unsubscribe();Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the synchronization function
async function ____() { /* send queue to server */ }
async function syncQueue() { /* send queue to server */ }
Explanation: syncQueue synchronizes the queue.
2 When is synchronization started?
NetInfo.addEventListener((state) => { if (state.???) syncQueue(); })- type === 'wifi'
- isInternetReachable === false
- details
- isConnected Correct answer
Explanation: Synchronization starts when isConnected becomes true.
3 Match each step to its purpose
| Term | Meaning |
|---|---|
NetInfo.addEventListener |
Listens to network change |
syncQueue |
Sends the queue |
isConnected |
Connection state |
unsubscribe |
Removes the subscription |