React Native and Expo quickstart
Build an iOS and Android screen that reads a public BTC-USDT REST price and subscribes to WebSocket prices with okx-api. No API key is needed. Prices are BTC-USDT last traded prices.
Use Node.js 24 and npm, with an iOS simulator or Android emulator and a matching Expo Go installation. iOS simulators require macOS and Xcode; Android virtual devices can be created with Android Studio or the Android SDK command-line tools. You can also view the complete OKX Expo example on GitHub.
See Runtime compatibility for runtime requirements.
These examples use public market data. Keep authenticated account and trading calls on your server. See Runtime setup for the scope of each recipe; a successful build does not verify live exchange access.
Create the project
mkdir okx-expo-quickstart
cd okx-expo-quickstart1. Create package.json
Declare the SDK dependency and the commands used by this project.
{
"name": "okx-expo-quickstart",
"private": true,
"type": "module",
"scripts": {
"start": "expo start",
"ios": "expo start --ios",
"android": "expo start --android"
},
"dependencies": {
"okx-api": "latest",
"expo": "58.0.23",
"react": "19.3.0",
"react-native": "0.88.1",
"buffer": "6.0.3",
"events": "3.3.0",
"https-browserify": "1.0.0",
"stream-http": "3.2.0",
"url": "0.11.4"
},
"main": "index.js"
}2. Create app.json
Name the Expo app and enable iOS and Android.
{
"expo": {
"name": "OKX price screen",
"slug": "okx-price-screen",
"version": "1.0.0",
"platforms": [
"ios",
"android"
]
}
}3. Install dependencies
Run this after saving package.json:
npm install4. Create siebly-sdk.metro.cjs
Resolve Node-style HTTP imports to the configured React Native polyfills.
module.exports = function configureSdkMetro(config, projectRoot) {
const aliases = {
https: require.resolve('https-browserify', { paths: [projectRoot] }),
http: require.resolve('stream-http', { paths: [projectRoot] }),
url: require.resolve('url/', { paths: [projectRoot] }),
};
const previousResolveRequest = config.resolver.resolveRequest;
config.resolver.resolveRequest = (context, moduleName, platform) => {
if (aliases[moduleName]) {
return { type: 'sourceFile', filePath: aliases[moduleName] };
}
const resolveRequest = previousResolveRequest || context.resolveRequest;
return resolveRequest(context, moduleName, platform);
};
return config;
};5. Create metro.config.cjs
Apply the SDK resolver to Expo’s default Metro configuration.
const { getDefaultConfig } = require('expo/metro-config');
const configureSdkMetro = require('./siebly-sdk.metro.cjs');
const config = getDefaultConfig(__dirname);
module.exports = configureSdkMetro(config, __dirname);6. Create App.js
Build the native screen. Its effect reads the price, subscribes to updates and closes the connection when the price panel unmounts.
import React, { useEffect, useState } from 'react';
import { Button, SafeAreaView, Text, View } from 'react-native';
import { RestClient, WebsocketClient } from 'okx-api';
function Prices() {
const [restPrice, setRestPrice] = useState('Loading');
const [livePrice, setLivePrice] = useState('Connecting');
const [error, setError] = useState('');
useEffect(() => {
let mounted = true;
const ws = new WebsocketClient();
function showError(error) {
console.error(error);
if (mounted) {
setError(error instanceof Error ? error.message : String(error));
}
}
async function loadPrice() {
const client = new RestClient();
const tickers = await client.getTicker({ instId: 'BTC-USDT' });
const price = tickers[0]?.last;
if (!price) {
throw new Error('No price was returned.');
}
if (mounted) {
setRestPrice(String(price));
}
}
loadPrice().catch(showError);
const timeout = setTimeout(() => {
showError(new Error('No BTC-USDT update within 30 seconds.'));
}, 30_000);
ws.on('update', (message) => {
if (message.arg?.channel !== 'tickers') {
console.log('WebSocket update:', message);
return;
}
const price = message.data?.[0]?.last;
if (mounted && price) {
clearTimeout(timeout);
setLivePrice(String(price));
}
});
ws.on('exception', showError);
// React can clean up an effect before its subscription starts.
Promise.resolve().then(async () => {
if (!mounted) {
return;
}
try {
await Promise.all(ws.subscribe({ channel: 'tickers', instId: 'BTC-USDT' }));
} finally {
// Close again if pending setup completed after unmount.
if (!mounted) {
ws.closeAll();
}
}
}).catch(showError);
return () => {
mounted = false;
clearTimeout(timeout);
ws.closeAll();
};
}, []);
return (
<View style={{ gap: 12, paddingVertical: 24 }}>
<Text>BTC-USDT REST price: {restPrice}</Text>
<Text>BTC-USDT WebSocket price: {livePrice}</Text>
<Text accessibilityRole="alert">{error}</Text>
</View>
);
}
export default function App() {
const [running, setRunning] = useState(true);
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ padding: 24 }}>
<Text style={{ fontSize: 24 }}>BTC-USDT price</Text>
{running ? (
<Prices />
) : (
<Text style={{ paddingVertical: 24 }}>
Stream stopped. WebSocket closed.
</Text>
)}
<Button
title={running ? 'Stop stream' : 'Start stream'}
onPress={() => setRunning(!running)}
/>
</View>
</SafeAreaView>
);
}7. Create index.js
Register the native app entry point with Expo.
import { registerRootComponent } from 'expo';
import App from './App';
registerRootComponent(App);Run on iOS or Android
npm startPress i to open the iOS simulator or a to open the Android emulator. Keep Expo Go in the foreground. The screen shows BTC-USDT REST price and BTC-USDT WebSocket price, each followed by a positive price such as 65000.5.
Tap Stop stream. The price component unmounts, its effect cleanup calls closeAll(), and the screen shows Stream stopped. WebSocket closed. Tap Start stream to create a new subscription. Late REST responses are ignored after unmount.
For apps that move between the foreground and background, use React Native’s AppState API to stop connections when the app is inactive and reload account or market state before reconnecting.
Troubleshooting
- An unresolved
events,https,http,urlorbufferimport means a dependency or Metro helper is missing. Install all dependencies and keepmetro.config.cjsbesidepackage.json. - If Metro still reports an import error after you fix the dependencies or configuration, stop it and run
npx expo start --clearfrom the project directory. - If Expo Go rejects the project version, use the Expo Go release that supports the starter's Expo SDK. Match Expo Go to the Expo SDK version in
package.json. - If price fields stay at Loading or Connecting, check internet access from the simulator or emulator and inspect the error shown on the screen. Exchange regional restrictions apply there too.