To connect to Frappe's WebSocket and receive real-time updates when a document of a particular DocType is saved, you can use the socket.io-client
library in your React Native app. Here's an example of a single-component app that demonstrates how to connect to the WebSocket, authenticate with an API key, and receive updates for a specific DocType:
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import io from 'socket.io-client';
const API_KEY = 'your_api_key'; // Replace with your actual API key
const SITE_NAME = 'your_site_name'; // Replace with your site name
const DOCTYPE = 'your_doctype'; // Replace with the DocType you want to monitor
const App = () => {
const [socket, setSocket] = useState(null);
const [documents, setDocuments] = useState([]);
useEffect(() => {
const initSocket = async () => {
const host = `https://${window.location.hostname}/${SITE_NAME}`; // Replace with your Frappe server URL
const newSocket = io(host, {
transports: ['websocket'],
reconnectionAttempts: 5,
extraHeaders: {
Authorization: `token ${API_KEY}`, // Authenticate with API key
},
});
newSocket.on('connect', () => {
console.log('Connected to Frappe WebSocket');
newSocket.emit('doctype_subscribe', DOCTYPE); // Subscribe to the DocType
});
newSocket.on('disconnect', () => {
console.log('Disconnected from Frappe WebSocket');
});
newSocket.on('list_update', (data) => {
if (data.doctype === DOCTYPE) {
// Update the documents state with the latest data
setDocuments(data.modified);
}
});
setSocket(newSocket);
};
initSocket();
return () => {
if (socket) {
socket.disconnect();
}
};
}, []);
return (
<View style={styles.container}>
<Text style={styles.title}>Updated Documents</Text>
{documents.map((doc) => (
<Text key={doc.name} style={styles.document}>
{doc.name}
</Text>
))}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 20,
},
document: {
fontSize: 16,
marginVertical: 5,
},
});
export default App;
Here's a breakdown of what's happening in the code:
- The app imports the necessary components and libraries, including
socket.io-client
. - The
API_KEY
,SITE_NAME
, andDOCTYPE
constants are defined at the top. Replace their values with your actual API key, site name, and the DocType you want to monitor, respectively. - The
App
component is defined as a functional component. - The
socket
state variable is used to store the WebSocket instance, and thedocuments
state variable is used to store the updated documents. - The
useEffect
hook is used to initialize the WebSocket connection when the component mounts. - Inside the
initSocket
function, a new WebSocket instance is created usingio
from thesocket.io-client
library. Thehost
variable is constructed using the site name and the current hostname. TheextraHeaders
option is used to pass the API key for authentication. - Event listeners are set up for various WebSocket events:
connect
: Logs a message when the connection is established and subscribes to the specified DocType.disconnect
: Logs a message when the connection is disconnected.list_update
: Listens for updates related to the specified DocType and updates thedocuments
state accordingly.
- The
setSocket
function is called to store the WebSocket instance in thesocket
state variable. - The
useEffect
hook also includes a cleanup function that disconnects the WebSocket instance when the component unmounts. - The component renders a list of updated document names based on the
documents
state.
To use this component in your React Native app, you'll need to replace the API_KEY
, SITE_NAME
, and DOCTYPE
constants with your actual values. Additionally, ensure that you have the necessary permissions to subscribe to the specified DocType and that your API key has the required access.
Note that this example assumes you're using Frappe's WebSocket server and that the server is configured to accept WebSocket connections from your React Native app. You may need to adjust the code based on your specific Frappe setup and requirements.