@sync-vault-js/react-native
v1.0.0
Published
React Native integration for SyncVault - AsyncStorage adapter and React Native utilities
Readme
@sync-vault-js/react-native
React Native integration for SyncVault - Provides AsyncStorage adapter and React Native-specific utilities for offline-first sync.
Installation
npm install @sync-vault-js/react-native @sync-vault-js/core @react-native-async-storage/async-storage @react-native-community/netinfo
# or
yarn add @sync-vault-js/react-native @sync-vault-js/core @react-native-async-storage/async-storage @react-native-community/netinfo
# or
pnpm add @sync-vault-js/react-native @sync-vault-js/core @react-native-async-storage/async-storage @react-native-community/netinfoPeer Dependencies
@sync-vault-js/core- Core SyncVault package (required)@react-native-async-storage/async-storage- Storage adapter (required)@react-native-community/netinfo- Network detection (optional, but recommended)
Quick Start
Option 1: Using the Convenience Function (Recommended)
The easiest way to get started is using createReactNativeSyncVault():
import AsyncStorage from '@react-native-async-storage/async-storage';
import NetInfo from '@react-native-community/netinfo';
import { createReactNativeSyncVault } from '@sync-vault-js/react-native';
// Create a SyncVault instance configured for React Native
const vault = createReactNativeSyncVault({
asyncStorage: AsyncStorage,
netInfo: NetInfo,
debug: true,
retry: {
maxRetries: 3,
initialDelay: 1000,
},
});
// Make requests - automatically queued when offline
const response = await vault.post('/api/users', {
name: 'John Doe',
email: '[email protected]',
});
// Check if request was queued
if (response.fromQueue) {
console.log('Request queued for later sync');
}Option 2: Manual Configuration
For more control, you can configure storage and network separately:
import AsyncStorage from '@react-native-async-storage/async-storage';
import NetInfo from '@react-native-community/netinfo';
import { createSyncVault } from '@sync-vault-js/core';
import {
createAsyncStorageAdapter,
createReactNativeNetworkChecker,
} from '@sync-vault-js/react-native';
// Create storage adapter
const storage = createAsyncStorageAdapter(AsyncStorage);
// Create network checker
const networkChecker = createReactNativeNetworkChecker(NetInfo);
// Create SyncVault instance
const vault = createSyncVault({
storage,
networkChecker,
debug: true,
});Usage with React
You can use the React hooks from @sync-vault-js/core/react with the React Native package:
import AsyncStorage from '@react-native-async-storage/async-storage';
import NetInfo from '@react-native-community/netinfo';
import { useSyncVault } from '@sync-vault-js/core/react';
import { createAsyncStorageAdapter, createReactNativeNetworkChecker } from '@sync-vault-js/react-native';
import { createSyncVault } from '@sync-vault-js/core';
// Create instance with React Native adapters
const vault = createSyncVault({
storage: createAsyncStorageAdapter(AsyncStorage),
networkChecker: createReactNativeNetworkChecker(NetInfo),
});
function MyComponent() {
const { isOnline, isProcessing, queueLength, post } = useSyncVault();
const handleSubmit = async (data) => {
const response = await post('/api/data', data);
if (response.fromQueue) {
Alert.alert('Saved offline', 'Will sync when online');
}
};
return (
<View>
<Text>Status: {isOnline ? 'Online' : 'Offline'}</Text>
<Text>Queue: {queueLength} pending</Text>
<Button onPress={() => handleSubmit({ name: 'Test' })} title="Submit" />
</View>
);
}API Reference
createReactNativeSyncVault(options)
Convenience function that creates a fully configured SyncVault instance for React Native.
Parameters:
options.asyncStorage- AsyncStorage instance from@react-native-async-storage/async-storageoptions.netInfo- NetInfo instance from@react-native-community/netinfooptions.*- All otherSyncVaultConfigoptions (see core documentation)
Returns: SyncVault instance
createAsyncStorageAdapter(asyncStorage)
Creates an AsyncStorage-based storage adapter.
Parameters:
asyncStorage- AsyncStorage instance from@react-native-async-storage/async-storage
Returns: AsyncStorageAdapter instance
createReactNativeNetworkChecker(netInfo)
Creates a network checker using React Native NetInfo.
Parameters:
netInfo- NetInfo instance from@react-native-community/netinfo
Returns: NetworkChecker instance
AsyncStorageAdapter
Storage adapter implementation that uses AsyncStorage for persistence.
Methods:
init()- Initialize the storageadd(job)- Add a job to the queuegetAll()- Get all pending jobsget(id)- Get a specific jobupdate(id, updates)- Update a jobremove(id)- Remove a jobcount()- Get count of pending jobsclear()- Clear all jobsmoveToDLQ(job)- Move a job to Dead Letter QueuegetDLQ()- Get all jobs in Dead Letter QueueclearDLQ()- Clear Dead Letter Queueclose()- Close the storage
Storage Details
The AsyncStorage adapter stores data using the following keys:
@syncvault:queue- Main queue storage@syncvault:dlq- Dead Letter Queue storage
Jobs are stored as JSON arrays and automatically sorted by timestamp to maintain FIFO ordering.
Examples
Basic Usage
import AsyncStorage from '@react-native-async-storage/async-storage';
import NetInfo from '@react-native-community/netinfo';
import { createReactNativeSyncVault } from '@sync-vault-js/react-native';
const vault = createReactNativeSyncVault({
asyncStorage: AsyncStorage,
netInfo: NetInfo,
});
// Make requests
await vault.post('/api/users', { name: 'John' });
await vault.get('/api/users');With Custom Configuration
const vault = createReactNativeSyncVault({
asyncStorage: AsyncStorage,
netInfo: NetInfo,
retry: {
maxRetries: 5,
initialDelay: 2000,
maxDelay: 60000,
},
queue: {
concurrency: 2,
processingDelay: 500,
},
debug: true,
});Event Handling
vault.on('network_offline', () => {
console.log('Device went offline');
});
vault.on('network_online', () => {
console.log('Device came online - processing queue');
});
vault.on('job_success', (event) => {
console.log('Job completed:', event.data.job.id);
});
vault.on('job_failed', (event) => {
if (!event.data.willRetry) {
console.error('Job failed permanently:', event.data.error);
}
});Migration from Core Package
If you were previously using the core package with manual setup:
Before:
import { createSyncVault, createReactNativeNetworkChecker } from '@sync-vault-js/core';
// Had to use MemoryAdapter (no persistence)After:
import { createReactNativeSyncVault } from '@sync-vault-js/react-native';
// Now has persistent storage with AsyncStorageTroubleshooting
AsyncStorage not found
Make sure you've installed @react-native-async-storage/async-storage:
npm install @react-native-async-storage/async-storageFor iOS, you may need to run:
cd ios && pod installNetwork detection not working
Ensure @react-native-community/netinfo is installed and properly linked:
npm install @react-native-community/netinfo
cd ios && pod install # For iOSStorage not persisting
AsyncStorage may have size limitations. If you're storing large amounts of data, consider:
- Clearing old jobs periodically
- Implementing custom storage with a different backend
- Using the DLQ to manage failed jobs
Related Packages
@sync-vault-js/core- Core SyncVault package@sync-vault-js/core/react- React hooks integration
Contributing
Contributions are welcome! We appreciate your help in making this project better.
How to Contribute
- Fork the repository and clone it locally
- Create a branch for your feature or bug fix:
git checkout -b feature/your-feature-name - Make your changes and ensure they follow the project's code style
- Add tests if applicable
- Run the build and type checking:
npm run build npm run typecheck - Commit your changes with a clear message
- Push to your fork and create a Pull Request
Development Setup
# Install dependencies
npm install
# Run in development mode (watch mode)
npm run dev
# Build the package
npm run build
# Run type checking
npm run typecheckReporting Issues
If you find a bug or have a feature request, please open an issue on GitHub with:
- A clear description of the problem or feature
- Steps to reproduce (for bugs)
- Expected vs actual behavior
- Environment details (React Native version, Node version, etc.)
Code Style
- Follow TypeScript best practices
- Use meaningful variable and function names
- Add comments for complex logic
- Ensure all code is properly typed
License
MIT © SyncVault
Authors
Nabhodipta Garai
- GitHub: @brownboycodes
- LinkedIn: Nabhodipta Garai

