react-native-simple-queue
v0.1.2
Published
Offline request queue for React Native
Maintainers
Readme
React Native Simple Queue 🚀
Offline-first, persistent request queue for React Native.
This library automatically queues API requests when the user is offline and processes them when the internet connection is restored. It persists the queue to AsyncStorage, so requests are not lost even if the app is closed.
✨ Features
- 🔌 Offline First: Queues requests automatically when there is no internet.
- 💾 Persistent: Uses
AsyncStorageto save requests (won't be lost on app restart). - 🔄 Auto Sync: Easy integration with
NetInfoto auto-retry when online. - 📘 TypeScript: Fully typed for excellent developer experience.
- 🪶 Lightweight: Zero bloat, simple logic.
📦 Installation
npm install react-native-simple-queue
Peer Dependencies
You need to install these packages if you haven't already:
npm install @react-native-async-storage/async-storage @react-native-community/netinfo
🚀 Usage
1. Setup the Listener
In your root component (e.g., App.tsx), listen for connection changes to process the queue automatically.
import React, { useEffect } from 'react';
import NetInfo from '@react-native-community/netinfo';
import { queue } from 'react-native-simple-queue';
export default function App() {
useEffect(() => {
const unsubscribe = NetInfo.addEventListener(state => {
if (state.isConnected) {
// Internet is back! Process the queue.
queue.processQueue()
.then(sentItems => {
if (sentItems.length > 0) {
console.log('Synced items:', sentItems);
}
});
}
});
return () => unsubscribe();
}, []);
return <YourApp />;
}2. Add a Request
Replace your standard fetch or axios calls with queue.addRequest.
import { queue } from 'react-native-simple-queue';
const sendData = async () => {
const response = await queue.addRequest(
'https://api.example.com/posts',
'POST',
{ title: 'Hello World', userId: 1 },
{ Authorization: 'Bearer token123' } // Optional headers
);
if (response.queued) {
console.log('User is offline. Request has been queued!');
} else {
console.log('Success! Response from server:', response);
}
};📚 API Reference
queue.addRequest(url, method, body, headers)
Adds a request to the queue (if offline) or sends it immediately (if online).
| Param | Type | Description |
|---|---|---|
| url | string | The API endpoint URL. |
| method | string | HTTP Method (GET, POST, PUT, DELETE, etc.). |
| body | any | The payload (automatically stringified). |
| headers | object | Optional request headers. |
queue.processQueue()
Manually triggers the processing of the queue. It checks for internet connection first.
Returns a Promise that resolves to an array of successfully sent items.
🤝 Contributing
Contributions are welcome! Please see CONTRIBUTING.md for details.
📄 License
MIT © Aziz
