React Native implementation layer for the Taro cross-platform framework, providing React Native-specific APIs and utilities.
—
HTTP request functionality, file upload/download, WebSocket connections, and network status monitoring for Taro React Native applications.
Make HTTP requests with comprehensive configuration options and Promise support.
/**
* Make an HTTP request
* @param options Request configuration options
* @returns RequestTask with abort capability
*/
function request<T = any>(options: {
url: string;
data?: any;
header?: Record<string, string>;
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'TRACE' | 'CONNECT';
dataType?: 'json' | 'text' | 'base64' | 'arraybuffer';
responseType?: 'text' | 'arraybuffer';
timeout?: number;
enableHttp2?: boolean;
enableQuic?: boolean;
enableCache?: boolean;
success?: (res: {
data: T;
statusCode: number;
header: Record<string, string>;
}) => void;
fail?: (res: TaroGeneral.CallbackResult) => void;
complete?: (res: any) => void;
}): Taro.RequestTask<T>;
interface RequestTask<T> extends Promise<{
data: T;
statusCode: number;
header: Record<string, string>;
}> {
/**
* Abort the request
*/
abort(): void;
}Usage Examples:
import { request } from "@tarojs/taro-rn";
// Simple GET request
const response = await request({
url: 'https://api.example.com/users',
method: 'GET'
});
console.log('Users:', response.data);
// POST request with data
const createResponse = await request({
url: 'https://api.example.com/users',
method: 'POST',
data: {
name: 'John Doe',
email: 'john@example.com'
},
header: {
'Content-Type': 'application/json'
}
});
// Request with custom headers and timeout
const authResponse = await request({
url: 'https://api.example.com/profile',
method: 'GET',
header: {
'Authorization': 'Bearer token123',
'Accept': 'application/json'
},
timeout: 10000
});
// Handle different response types
const imageResponse = await request({
url: 'https://example.com/image.jpg',
responseType: 'arraybuffer'
});
// Abortable request
const requestTask = request({
url: 'https://api.example.com/large-data',
timeout: 30000
});
// Abort after 5 seconds
setTimeout(() => {
requestTask.abort();
}, 5000);
try {
const result = await requestTask;
console.log('Request completed:', result);
} catch (error) {
console.log('Request aborted or failed:', error);
}Upload files to remote servers with progress tracking.
/**
* Upload files to a remote server
* @param options Upload configuration options
*/
function uploadFile(options: {
url: string;
filePath: string;
name: string;
header?: Record<string, string>;
formData?: Record<string, any>;
timeout?: number;
success?: (res: {
data: string;
statusCode: number;
}) => void;
fail?: (res: TaroGeneral.CallbackResult) => void;
complete?: (res: any) => void;
}): Taro.UploadTask;
interface UploadTask extends Promise<{
data: string;
statusCode: number;
}> {
/**
* Monitor upload progress
* @param callback Progress callback
*/
progress(callback: (res: {
progress: number;
totalBytesSent: number;
totalBytesExpectedToSend: number;
}) => void): void;
/**
* Abort the upload
*/
abort(): void;
}Download files from remote servers with progress tracking.
/**
* Download files from a remote server
* @param options Download configuration options
*/
function downloadFile(options: {
url: string;
header?: Record<string, string>;
timeout?: number;
filePath?: string;
success?: (res: {
tempFilePath: string;
filePath?: string;
statusCode: number;
}) => void;
fail?: (res: TaroGeneral.CallbackResult) => void;
complete?: (res: any) => void;
}): Taro.DownloadTask;
interface DownloadTask extends Promise<{
tempFilePath: string;
filePath?: string;
statusCode: number;
}> {
/**
* Monitor download progress
* @param callback Progress callback
*/
progress(callback: (res: {
progress: number;
totalBytesWritten: number;
totalBytesExpectedToWrite: number;
}) => void): void;
/**
* Abort the download
*/
abort(): void;
}Usage Examples:
import { uploadFile, downloadFile } from "@tarojs/taro-rn";
// Upload file with progress tracking
const uploadTask = uploadFile({
url: 'https://api.example.com/upload',
filePath: '/path/to/local/file.jpg',
name: 'file',
formData: {
'user_id': '123',
'category': 'avatar'
}
});
uploadTask.progress((res) => {
console.log('Upload progress:', res.progress);
console.log('Bytes sent:', res.totalBytesSent);
});
const uploadResult = await uploadTask;
console.log('Upload complete:', uploadResult);
// Download file with progress tracking
const downloadTask = downloadFile({
url: 'https://example.com/file.pdf',
header: {
'Authorization': 'Bearer token123'
}
});
downloadTask.progress((res) => {
console.log('Download progress:', res.progress);
});
const downloadResult = await downloadTask;
console.log('Downloaded to:', downloadResult.tempFilePath);Establish WebSocket connections for real-time communication.
/**
* Connect to a WebSocket server
* @param options WebSocket connection options
*/
function connectSocket(options: {
url: string;
header?: Record<string, any>;
protocols?: string[];
timeout?: number;
success?: (res: TaroGeneral.CallbackResult) => void;
fail?: (res: TaroGeneral.CallbackResult) => void;
complete?: (res: any) => void;
}): Taro.SocketTask;
interface SocketTask {
/**
* Send data through the WebSocket
* @param options Send options
*/
send(options: {
data: string | ArrayBuffer;
success?: (res: TaroGeneral.CallbackResult) => void;
fail?: (res: TaroGeneral.CallbackResult) => void;
complete?: (res: any) => void;
}): void;
/**
* Close the WebSocket connection
* @param options Close options
*/
close(options?: {
code?: number;
reason?: string;
success?: (res: TaroGeneral.CallbackResult) => void;
fail?: (res: TaroGeneral.CallbackResult) => void;
complete?: (res: any) => void;
}): void;
/**
* Listen for WebSocket open event
* @param callback Open event callback
*/
onOpen(callback: (res: any) => void): void;
/**
* Listen for WebSocket close event
* @param callback Close event callback
*/
onClose(callback: (res: { code: number; reason: string }) => void): void;
/**
* Listen for WebSocket error event
* @param callback Error event callback
*/
onError(callback: (res: { errMsg: string }) => void): void;
/**
* Listen for WebSocket message event
* @param callback Message event callback
*/
onMessage(callback: (res: { data: string | ArrayBuffer }) => void): void;
}Usage Examples:
import { connectSocket } from "@tarojs/taro-rn";
// Connect to WebSocket
const socketTask = connectSocket({
url: 'wss://api.example.com/websocket',
header: {
'Authorization': 'Bearer token123'
}
});
// Set up event listeners
socketTask.onOpen((res) => {
console.log('WebSocket connected');
// Send initial message
socketTask.send({
data: JSON.stringify({ type: 'join', room: 'chat-room-1' })
});
});
socketTask.onMessage((res) => {
const message = JSON.parse(res.data as string);
console.log('Received message:', message);
});
socketTask.onError((res) => {
console.error('WebSocket error:', res.errMsg);
});
socketTask.onClose((res) => {
console.log('WebSocket closed:', res.code, res.reason);
});
// Send messages
socketTask.send({
data: JSON.stringify({
type: 'message',
content: 'Hello, world!'
})
});
// Close connection when done
socketTask.close({
code: 1000,
reason: 'Normal closure'
});Monitor network connectivity and type.
/**
* Get current network type
* @param options Network type options
*/
function getNetworkType(options?: {
success?: (res: {
networkType: 'wifi' | '2g' | '3g' | '4g' | '5g' | 'unknown' | 'none';
isConnected: boolean;
}) => void;
fail?: (res: TaroGeneral.CallbackResult) => void;
complete?: (res: any) => void;
}): Promise<{
networkType: 'wifi' | '2g' | '3g' | '4g' | '5g' | 'unknown' | 'none';
isConnected: boolean;
}>;
/**
* Listen to network status changes
* @param callback Network status change callback
*/
function onNetworkStatusChange(callback: (res: {
isConnected: boolean;
networkType: 'wifi' | '2g' | '3g' | '4g' | '5g' | 'unknown' | 'none';
}) => void): void;
/**
* Stop listening to network status changes
* @param callback Optional callback to remove specific listener
*/
function offNetworkStatusChange(callback?: (res: {
isConnected: boolean;
networkType: string;
}) => void): void;Usage Examples:
import {
getNetworkType,
onNetworkStatusChange,
offNetworkStatusChange
} from "@tarojs/taro-rn";
// Check current network status
const networkStatus = await getNetworkType();
console.log('Network type:', networkStatus.networkType);
console.log('Is connected:', networkStatus.isConnected);
// Adapt behavior based on network type
if (networkStatus.networkType === 'wifi') {
// High-quality content for WiFi
console.log('Load high-resolution images');
} else if (networkStatus.networkType === '2g' || networkStatus.networkType === '3g') {
// Optimized content for slower connections
console.log('Load compressed images');
}
// Listen for network changes
const networkChangeHandler = (res) => {
console.log('Network changed:', res.networkType, res.isConnected);
if (!res.isConnected) {
// Handle offline state
console.log('App is offline');
} else {
// Handle online state
console.log('App is back online');
}
};
onNetworkStatusChange(networkChangeHandler);
// Clean up listener when done
// offNetworkStatusChange(networkChangeHandler);Install with Tessl CLI
npx tessl i tessl/npm-tarojs--taro-rn