@nosql-ai/react-native
v1.0.0
Published
Official React Native SDK for NoSQL with offline-first capabilities and mobile optimization
Maintainers
Readme
NoSQL React Native SDK
Official React Native SDK for NoSQL with offline-first capabilities and mobile optimization.
Features
- 📱 Mobile-Optimized: Built specifically for iOS and Android
- 📴 Offline-First: AsyncStorage caching with automatic sync
- 🔄 Real-time Updates: WebSocket subscriptions
- 📶 Network Detection: Automatic online/offline handling with NetInfo
- 🎣 React Hooks: Mobile-optimized hooks for all operations
- ⚡ Background Sync: Queue operations offline, sync when online
- 🔋 Battery Efficient: Optimized for mobile battery life
- 📦 TypeScript: Full type safety
Installation
npm install @nosql-ai/react-native @nosql-ai/sdk
# or
yarn add @nosql-ai/react-native @nosql-ai/sdkInstall peer dependencies:
npm install @react-native-async-storage/async-storage @react-native-community/netinfo
# or
yarn add @react-native-async-storage/async-storage @react-native-community/netinfoiOS Setup
cd ios && pod installQuick Start
1. Setup Provider
import { NoSQLClient } from '@nosql-ai/sdk';
import { NoSQLProvider } from '@nosql-ai/react-native';
const client = new NoSQLClient({
endpoint: 'https://nosql-db-prod.finhub.workers.dev',
apiKey: 'your-api-key'
});
function App() {
return (
<NoSQLProvider client={client}>
<YourApp />
</NoSQLProvider>
);
}2. Use in Components
import { useDocument } from '@nosql-ai/react-native';
import { View, Text, Button } from 'react-native';
function UserProfile({ userId }) {
const { data, loading, update } = useDocument({
database: 'mydb',
collection: 'users',
id: userId,
subscribe: true
});
if (loading) return <Text>Loading...</Text>;
return (
<View>
<Text>{data.name}</Text>
<Button
title="Update Profile"
onPress={() => update({ lastSeen: Date.now() })}
/>
</View>
);
}Hooks
useDocument
Fetch and manage documents with offline support:
const { data, loading, error, insert, update, remove } = useDocument({
database: 'mydb',
collection: 'users',
id: 'user-123',
subscribe: true, // Real-time updates
cacheKey: 'user-profile' // Custom cache key
});
// Insert document (works offline!)
await insert({ name: 'John', age: 30 });
// Update document
await update({ age: 31 });
// Delete document
await remove();useVectorSearch
AI-powered similarity search:
const { results, loading, search, generateEmbedding } = useVectorSearch({
database: 'mydb',
collection: 'embeddings',
query: {
vector: [0.1, 0.2, 0.3],
topK: 10,
metric: 'cosine'
},
autoSearch: true,
cacheResults: true // Cache for offline access
});
// Generate embedding from text
const embedding = await generateEmbedding('machine learning');
// Search with new query
await search({ vector: embedding, topK: 5 });useSubscription
Real-time data subscriptions:
const { data, connected, messages } = useSubscription({
channel: 'documents:mydb:users',
filter: { active: true },
enabled: true
});
// Latest update
console.log('Latest:', data);
// All messages
console.log('All updates:', messages);
// Connection status
console.log('Connected:', connected);useOfflineStorage
Direct cache management:
const { cachedData, loading, setCachedData, clearCache, getCacheSize } = useOfflineStorage('my-key');
// Save to cache
await setCachedData({ foo: 'bar' });
// Clear cache
await clearCache();
// Get total cache size
const size = await getCacheSize();
console.log(`Cache size: ${size} bytes`);Real-World Examples
Offline-First Todo App
import { useDocument } from '@nosql-ai/react-native';
import { FlatList, Text, TouchableOpacity, View } from 'react-native';
function TodoList() {
const { data: todos, loading, insert, update } = useDocument({
database: 'todos',
collection: 'items',
query: { filter: { completed: false } },
subscribe: true
});
const addTodo = async (text) => {
// Works offline! Syncs when connection restored
await insert({
text,
completed: false,
createdAt: Date.now()
});
};
const toggleTodo = async (todo) => {
await update({
_id: todo._id,
completed: !todo.completed
});
};
return (
<FlatList
data={todos}
renderItem={({ item }) => (
<TouchableOpacity onPress={() => toggleTodo(item)}>
<Text>{item.text}</Text>
</TouchableOpacity>
)}
/>
);
}Live Chat App
import { useSubscription, useDocument } from '@nosql-ai/react-native';
import { FlatList, Text, TextInput, Button } from 'react-native';
function ChatRoom({ roomId }) {
const [message, setMessage] = useState('');
const { messages } = useSubscription({
channel: `chat:${roomId}`,
enabled: true
});
const { insert } = useDocument({
database: 'chat',
collection: 'messages'
});
const sendMessage = async () => {
await insert({
roomId,
text: message,
timestamp: Date.now()
});
setMessage('');
};
return (
<>
<FlatList
data={messages}
renderItem={({ item }) => <Text>{item.text}</Text>}
/>
<TextInput
value={message}
onChangeText={setMessage}
/>
<Button title="Send" onPress={sendMessage} />
</>
);
}Semantic Image Search
import { useVectorSearch } from '@nosql-ai/react-native';
import { Image, FlatList, TextInput } from 'react-native';
function ImageSearch() {
const [query, setQuery] = useState('');
const { results, loading, search, generateEmbedding } = useVectorSearch({
database: 'photos',
collection: 'images',
query: { vector: [], topK: 20 },
autoSearch: false
});
const handleSearch = async () => {
const embedding = await generateEmbedding(query);
await search({ vector: embedding, topK: 20 });
};
return (
<>
<TextInput
value={query}
onChangeText={setQuery}
placeholder="Search photos..."
onSubmitEditing={handleSearch}
/>
<FlatList
data={results}
numColumns={3}
renderItem={({ item }) => (
<Image
source={{ uri: item.metadata.url }}
style={{ width: 100, height: 100 }}
/>
)}
/>
</>
);
}Network Status Indicator
import { useNoSQLContext } from '@nosql-ai/react-native';
import { View, Text } from 'react-native';
function NetworkBanner() {
const { isOnline, connectionType } = useNoSQLContext();
if (isOnline) return null;
return (
<View style={{ backgroundColor: 'orange', padding: 10 }}>
<Text>📴 Offline Mode - Changes will sync when online</Text>
</View>
);
}Offline Support
The SDK handles offline scenarios automatically:
- ✅ AsyncStorage Caching: All data cached locally
- ✅ Offline Reads: Serve cached data when offline
- ✅ Network Detection: Automatic online/offline monitoring
- ✅ Background Sync: Operations queue and sync when online
- ✅ Conflict Resolution: Smart merge strategies
- ✅ Battery Optimization: Efficient network usage
Network Types
Access detailed network information:
const { isOnline, connectionType } = useNoSQLContext();
// connectionType can be:
// - 'wifi'
// - 'cellular'
// - 'bluetooth'
// - 'ethernet'
// - 'wimax'
// - 'vpn'
// - 'none'
// - 'unknown'Performance Optimization
Reduce Data Transfer
// Use projections to fetch only needed fields
const { data } = useDocument({
database: 'mydb',
collection: 'users',
query: {
filter: { active: true },
projection: ['name', 'email'], // Only fetch name and email
limit: 20 // Limit results
}
});Cache Management
const { getCacheSize, clearAllCache } = useOfflineStorage('key');
// Monitor cache size
const size = await getCacheSize();
if (size > 10 * 1024 * 1024) { // 10MB
await clearAllCache();
}Optimize Real-time Subscriptions
// Only subscribe when screen is focused
const isFocused = useIsFocused();
const { data } = useSubscription({
channel: 'updates',
enabled: isFocused // Disable when screen not visible
});TypeScript Support
Full TypeScript support with type inference:
interface User {
_id: string;
name: string;
email: string;
age: number;
}
const { data } = useDocument<User>({
database: 'mydb',
collection: 'users',
id: 'user-123'
});
// data is typed as User!
console.log(data?.name.toUpperCase());Best Practices
- Enable Offline Mode: Always enable offline support for mobile
- Cache Strategically: Use meaningful cache keys
- Handle Loading States: Mobile users expect instant feedback
- Optimize Images: Compress before uploading
- Monitor Cache Size: Clear old data periodically
- Test Offline: Always test with airplane mode
- Battery Awareness: Disable subscriptions in background
Platform Support
- ✅ iOS: 13.0+
- ✅ Android: API 21+ (Android 5.0+)
- ✅ React Native: 0.70+
Requirements
- React Native 0.70+
- @nosql-ai/sdk ^1.1.0
- @react-native-async-storage/async-storage ^2.0.0
- @react-native-community/netinfo ^11.0.0
Documentation
Visit https://nosql-docs-prod.finhub.workers.dev for complete documentation.
License
MIT © NoSQL Team
