### Start Example App Packager
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/CONTRIBUTING.md
Starts the Metro server for the example application. Changes to JavaScript code will be reflected without a rebuild, while native code changes require a rebuild.
```shell
yarn example start
```
--------------------------------
### Run Example App on Web
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/CONTRIBUTING.md
Builds and runs the example application on a web browser.
```shell
yarn example web
```
--------------------------------
### Run Example App on iOS
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/CONTRIBUTING.md
Builds and runs the example application on an iOS simulator or device.
```shell
yarn example ios
```
--------------------------------
### Install rn-firebase-chat using npm
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.md
Installs the core rn-firebase-chat package using npm. This is the basic installation command.
```sh
npm install rn-firebase-chat
```
--------------------------------
### Run Example App on Android
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/CONTRIBUTING.md
Builds and runs the example application on an Android device or emulator.
```shell
yarn example android
```
--------------------------------
### Install rn-firebase-chat Dependencies with npm
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.expo.md
Installs the `rn-firebase-chat` library and its peer dependencies, along with `expo-build-properties`, using npm. This command ensures all necessary packages are present for the Firebase integration.
```sh
npm install rn-firebase-chat @react-native-firebase/app @react-native-firebase/firestore @react-native-firebase/storage randomcolor react-native-aes-crypto react-native-gifted-chat react-native-keyboard-controller react-native-video react-native-vision-camera react-native-image-picker expo-build-properties --save
```
--------------------------------
### Install rn-firebase-chat Dependencies with Yarn
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.expo.md
Installs the `rn-firebase-chat` library and its peer dependencies, along with `expo-build-properties`, using Yarn. This command ensures all necessary packages are present for the Firebase integration.
```sh
yarn add rn-firebase-chat @react-native-firebase/app @react-native-firebase/firestore @react-native-firebase/storage randomcolor react-native-aes-crypto react-native-gifted-chat react-native-keyboard-controller react-native-video react-native-vision-camera react-native-image-picker expo-build-properties
```
--------------------------------
### Install chat addons dependencies using Yarn
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.md
Installs additional libraries for chat addons like image/video picker and camera using Yarn. Ensure these are installed before enabling addon features.
```sh
yarn add react-native-video react-native-vision-camera react-native-image-picker
```
--------------------------------
### Build Package
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Builds the package for distribution using yarn. This command is typically used before publishing.
```bash
yarn prepack
```
--------------------------------
### Install rn-firebase-chat with dependencies using Yarn
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.md
Installs rn-firebase-chat and its required dependencies using Yarn. This command ensures all necessary packages are added to your project.
```sh
yarn add rn-firebase-chat @react-native-firebase/app @react-native-firebase/firestore @react-native-firebase/storage randomcolor react-native-aes-crypto react-native-gifted-chat react-native-keyboard-controller
```
--------------------------------
### Install Project Dependencies with Yarn
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/CONTRIBUTING.md
Installs all the necessary dependencies for the project. It is recommended to use Yarn for development as the tooling is built around it.
```shell
yarn
```
--------------------------------
### Publish to npm
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Publishes the built package to the npm registry. Ensure you have logged in and the package is built.
```bash
npm publish
```
--------------------------------
### Bootstrap Project Dependencies and Pods
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/CONTRIBUTING.md
Installs all project dependencies and initializes CocoaPods for the iOS project, setting up the development environment.
```shell
yarn bootstrap
```
--------------------------------
### Install rn-firebase-chat with dependencies using npm
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.md
Installs rn-firebase-chat along with its essential React Native Firebase and other utility dependencies using npm. Ensure these dependencies are installed for full functionality.
```sh
npm install rn-firebase-chat @react-native-firebase/app @react-native-firebase/firestore @react-native-firebase/storage randomcolor react-native-aes-crypto react-native-gifted-chat react-native-keyboard-controller --save
```
--------------------------------
### Install chat addons dependencies using npm
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.md
Installs additional libraries required for the image/video picker and camera features within the chat addon. Use this command with npm.
```sh
npm install react-native-video react-native-vision-camera react-native-image-picker --save
```
--------------------------------
### Run Tests and Linting
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Executes the test suite, runs linters, and performs TypeScript type checking for the project.
```bash
yarn test
yarn lint
yarn typecheck
```
--------------------------------
### Check npm Login Status
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Verifies if you are currently logged into your npm account. If not, it prompts you to log in.
```bash
npm whoami
# If not logged in, use:
npm login
```
--------------------------------
### Check npm Package Version
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Retrieves the latest published version of the 'rn-firebase-chat' package from the npm registry. Useful for troubleshooting version conflicts.
```bash
npm view rn-firebase-chat version
```
--------------------------------
### Automated Minor Release with release-it
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Initiates an automated minor release for new features using the `release-it` tool. This command is used for backward-compatible feature additions.
```bash
yarn release minor
```
--------------------------------
### Dry Run of Automated Release
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Performs a dry run of the automated release process using `release-it`. This allows you to test the release steps without actually publishing to npm or creating tags.
```bash
yarn release:dry
```
--------------------------------
### Automated Major Release with release-it
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Initiates an automated major release for breaking changes using the `release-it` tool. This command should be used when introducing non-backward-compatible API changes.
```bash
yarn release major
```
--------------------------------
### Check Git Status
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Displays the current status of the working directory and staging area. Used to ensure a clean working tree before a release.
```bash
git status
```
--------------------------------
### Implement ChatScreen in React Native
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.md
Provides an example of how to render the base ChatScreen component. It takes member IDs and partner information as props to display the chat interface.
```javascript
import React from 'react';
import { ChatScreen as BaseChatScreen } from 'rn-firebase-chat';
const partnerInfo = {
id: 'ayz123',
name: 'Tony',
avatar: 'https://example.com/tony.jpg',
};
export const ChatScreen: React.FC = () => {
return (
);
};
```
--------------------------------
### Push Git Changes and Tags
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Pushes the committed changes and tags to the 'master' branch on the remote origin. This is typically done after a successful publish.
```bash
git push origin master --tags
```
--------------------------------
### Setup Chat Navigator in React Navigation
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.md
Configures the navigation stack for chat screens using React Navigation. This includes screens for listing conversations and the chat interface itself.
```javascript
export const ChatNavigator = () => (
);
```
--------------------------------
### Check Git Remote URL
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Displays the remote repository URLs configured for the local Git repository. Useful for troubleshooting push failures.
```bash
git remote -v
```
--------------------------------
### Manual Version Update
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/RELEASE.md
Manually updates the package version using npm. This command can be used for 'patch', 'minor', or 'major' version bumps.
```bash
npm version patch # or minor, major
```
--------------------------------
### Prebuild Expo Project for Native Configuration
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.expo.md
Executes the `expo prebuild --clean` command to generate or update the native Android and iOS projects. This command is crucial for applying the configured plugins and native settings defined in `app.config.ts` when using the Expo managed workflow.
```sh
expo prebuild --clean
```
--------------------------------
### Expo App Configuration with Firebase Plugins
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.expo.md
Configures the `app.config.ts` file for Expo to include necessary plugins for Firebase integration and other libraries. It specifies configurations for `expo-build-properties`, `react-native-video`, and `react-native-vision-camera`, which are essential for native module compatibility and functionality within Expo.
```typescript
// app.config.ts
import { ExpoConfig } from 'expo';
const config: ExpoConfig = {
name: 'YourAppName',
slug: 'your-app-slug',
plugins: [
// ...remaining config
// <-- Adding these values -->
'@react-native-firebase/app',
[
'expo-build-properties',
{
ios: {
useFrameworks: 'static',
},
},
],
[
'react-native-video',
{
enableNotificationControls: true,
androidExtensions: {
useExoplayerRtsp: false,
useExoplayerSmoothStreaming: false,
useExoplayerHls: false,
useExoplayerDash: false,
},
},
],
[
'react-native-vision-camera',
{
cameraPermissionText: '$(PRODUCT_NAME) needs access to your Camera.',
// optionally, if you want to record audio:
enableMicrophonePermission: true,
microphonePermissionText: '$(PRODUCT_NAME) needs access to your Microphone.',
},
],
// <-- Adding these values -->
],
};
export default config;
```
--------------------------------
### Firebase Configuration File Path in Expo Config
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.expo.md
Specifies the paths to the Firebase configuration files (`google-services.json` for Android and `GoogleService-Info.plist` for iOS) within the `app.config.ts` file. This allows EAS Build or local builds to correctly locate and use these files for Firebase initialization.
```typescript
// inside the same app.config.ts
ios: {
googleServicesFile: './ios/GoogleService-Info.plist',
},
android: {
googleServicesFile: './android/app/google-services.json',
},
```
--------------------------------
### Publish New Versions with Release-it
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/CONTRIBUTING.md
Publishes new versions of the package to npm. release-it automates tasks like version bumping, tagging, and release creation.
```shell
yarn release
```
--------------------------------
### Integrate Camera and Gallery addons in ChatScreen
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.md
Shows how to integrate camera and gallery functionalities into the ChatScreen component using the provided addons. This involves using the `useCamera` hook and configuring `inputToolbarProps`.
```javascript
import React from 'react'
import {ChatScreen as BaseChatScreen} from 'rn-firebase-chat'
import {CameraView, useCamera} from 'rn-firebase-chat/src/addons/camera'
...
export const ChatScreen: React.FC = () => {
const {onPressCamera, onPressGallery} = useCamera()
return (
{({onSend}) => ( )}
)
}
```
--------------------------------
### Verify Code with TypeScript and ESLint
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/CONTRIBUTING.md
Runs TypeScript for type checking and ESLint for linting the codebase to ensure code quality and consistency.
```shell
yarn typecheck
yarn lint
```
--------------------------------
### Run Unit Tests
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/CONTRIBUTING.md
Executes all unit tests defined for the project using Jest, ensuring the correctness of individual code components.
```shell
yarn test
```
--------------------------------
### Wrap App with ChatProvider in React Native
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.md
Demonstrates how to wrap your React Native application with the ChatProvider component. This component is essential for initializing chat functionalities and requires user information.
```javascript
import { ChatProvider } from 'rn-firebase-chat';
const userInfo = {
id: 'abc123',
name: 'John Doe',
avatar: 'https://example.com/avatar.jpg',
};
function App() {
return (
);
}
```
--------------------------------
### ChatScreen with Camera and Gallery Integration (JavaScript)
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
Extends the ChatScreen component to include camera and gallery functionalities for sending media. It utilizes the 'useCamera' hook from 'rn-firebase-chat/src/addons/camera' to manage media picker interactions. The input toolbar is configured with 'hasCamera' and 'hasGallery' props.
```javascript
import React from 'react';
import { ChatScreen } from 'rn-firebase-chat';
import { CameraView, useCamera } from 'rn-firebase-chat/src/addons/camera';
export const ChatWithMediaScreen = () => {
const { onPressCamera, onPressGallery } = useCamera();
const partnerInfo = {
id: 'user_99999',
name: 'Michael Brown',
avatar: 'https://example.com/avatars/michael.jpg',
};
return (
{({ onSend }) => (
)}
);
};
// Custom input toolbar styling
export const CustomStyledChatScreen = () => {
const { onPressCamera, onPressGallery } = useCamera();
const partnerInfo = {
id: 'user_88888',
name: 'Sarah Wilson',
avatar: 'https://example.com/avatars/sarah.jpg',
};
return (
{({ onSend }) => }
);
};
```
--------------------------------
### Integrate Camera and Gallery with useCamera Hook (React Native)
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
The `useCamera` hook facilitates integration with the device's camera and gallery for capturing and selecting media to be sent in chats. It returns functions to open these interfaces. Dependencies include 'react' and 'rn-firebase-chat/src/addons/camera'.
```javascript
import React from 'react';
import { View, Button } from 'react-native';
import { useCamera } from 'rn-firebase-chat/src/addons/camera';
export const MediaPickerButtons = ({ onMediaSelected }) => {
const { onPressCamera, onPressGallery } = useCamera();
const handleGalleryPress = async () => {
const result = await onPressGallery();
if (result) {
console.log('Selected media:', result);
// result = { type: 'image' | 'video', path: string, extension: string }
onMediaSelected?.(result);
}
};
return (
);
};
// Complete example with camera view and message sending
import { ChatScreen } from 'rn-firebase-chat';
import { CameraView, useCamera } from 'rn-firebase-chat/src/addons/camera';
export const FullMediaChatExample = () => {
const { onPressCamera, onPressGallery } = useCamera();
const partnerInfo = {
id: 'user_55555',
name: 'Emily Davis',
avatar: 'https://example.com/avatars/emily.jpg',
};
const handleMediaSend = async (mediaData) => {
console.log('Sending media:', mediaData);
// Media is automatically uploaded to Firebase Storage
// and message is created with the media URL
};
return (
console.log('Loading...')}
onLoadEnd={() => console.log('Loaded')}
>
{({ onSend }) => (
{
await onSend(media);
handleMediaSend(media);
}}
/>
)}
);
};
```
--------------------------------
### Implement ListConversationScreen in React Native
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/README.md
Shows how to use the ListConversationScreen component from rn-firebase-chat. It includes handling item press events to navigate to the chat screen.
```javascript
import React, { useCallback } from 'react';
import { ListConversationScreen } from 'rn-firebase-chat';
import { navigate } from '../../navigation/NavigationService';
import RouteKey from '../../navigation/RouteKey';
export const ListChatScreen: React.FC = () => {
const handleItemPress = useCallback((data) => {
navigate(RouteKey.ChatScreen, data);
}, []);
return ;
};
```
--------------------------------
### One-on-One and Group Chat with ChatScreen (JavaScript)
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
Implements one-on-one and group chat interfaces using the ChatScreen component. It handles message history, real-time updates, and can be configured with various props for partner information, notifications, and typing indicators. Group chats allow for custom conversation details.
```javascript
import React from 'react';
import { ChatScreen } from 'rn-firebase-chat';
import { useRoute } from '@react-navigation/native';
export const OneOnOneChatScreen = () => {
const route = useRoute();
const partnerInfo = {
id: 'user_67890',
name: 'Jane Smith',
avatar: 'https://example.com/avatars/jane.jpg',
};
const handleStartLoad = () => {
console.log('Loading messages...');
};
const handleLoadEnd = () => {
console.log('Messages loaded');
};
const handleSendNotification = () => {
// Trigger push notification to partner
console.log('Send push notification to partner');
};
return (
);
};
// Group chat with custom conversation info
export const GroupChatScreen = () => {
const memberIds = ['user_11111', 'user_22222', 'user_33333'];
const partners = [
{ id: 'user_11111', name: 'Alice', avatar: 'https://example.com/alice.jpg' },
{ id: 'user_22222', name: 'Bob', avatar: 'https://example.com/bob.jpg' },
{ id: 'user_33333', name: 'Charlie', avatar: 'https://example.com/charlie.jpg' },
];
const customConversationInfo = {
id: 'group_project_team',
name: 'Project Team',
image: 'https://example.com/group-avatar.jpg',
};
return (
);
};
```
--------------------------------
### Configure User Manually with FirestoreServices
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
Manually configures user information for FirestoreServices. This involves setting the user's ID, name, and avatar. It returns the configured userId upon successful completion.
```javascript
import { FirestoreServices } from 'rn-firebase-chat';
// Get the singleton instance
const firestoreService = FirestoreServices.getInstance();
// Configure user info manually
async function setupUserManually() {
const userInfo = {
id: 'user_advanced_001',
name: 'Advanced User',
avatar: 'https://example.com/advanced.jpg',
};
await firestoreService.configuration({ userInfo });
console.log('User configured:', firestoreService.userId);
}
```
--------------------------------
### Initialize Chat Context with ChatProvider in React Native
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
The ChatProvider component initializes the chat context for the application, managing Firebase connections, user authentication, and real-time data. It can be configured with basic settings or advanced security features like encryption and content filtering.
```javascript
import React from 'react';
import { ChatProvider } from 'rn-firebase-chat';
import { NavigationContainer } from '@react-navigation/native';
const userInfo = {
id: 'user_12345',
name: 'John Doe',
avatar: 'https://example.com/avatars/john.jpg',
};
// Basic setup without encryption
function App() {
return (
);
}
// Setup with message encryption and content filtering
function AppWithSecurity() {
const blackListWords = ['spam', 'inappropriate', 'badword'];
const encryptionOptions = {
salt: 'random-salt-string-minimum-16-chars',
iterations: 5000,
keyLength: 256,
};
return (
);
}
export default App;
```
--------------------------------
### Fix Code Formatting Errors
Source: https://github.com/saigontechnology/rn-firebase-chat/blob/master/CONTRIBUTING.md
Automatically fixes code formatting errors detected by ESLint, ensuring consistent code style across the project.
```shell
yarn lint --fix
```
--------------------------------
### Listen to Conversation Updates with FirestoreServices
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
Sets up a listener for real-time conversation updates using FirestoreServices. It provides a callback function that receives updated conversation data, including unread counts and the latest message. Returns a function to unsubscribe from updates.
```javascript
// Listen to conversation updates
function listenToConversationChanges() {
const unsubscribe = firestoreService.listenConversationUpdate((conversation) => {
console.log('Conversation updated:', conversation);
console.log('Unread count:', conversation.unRead);
console.log('Latest message:', conversation.latestMessage?.text);
});
// Clean up listener when done
return () => unsubscribe();
}
```
--------------------------------
### Access Chat Context with useChatContext Hook (React Native)
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
The `useChatContext` hook provides access to global chat context, including user information, chat state, and dispatch functions. It's essential for managing and updating chat-related data within your application. Dependencies include 'react' and 'react-native'.
```javascript
import React, { useEffect } from 'react';
import { View, Text, Button } from 'react-native';
import { useChatContext } from 'rn-firebase-chat';
export const ChatStatusComponent = () => {
const { userInfo, chatState, chatDispatch } = useChatContext();
return (
Current User: {userInfo?.name}User ID: {userInfo?.id}Active Conversations: {Object.keys(chatState).length}
);
};
// Access blacklist configuration
export const ContentFilterStatus = () => {
const { blackListWords } = useChatContext();
return (
Content filtering enabled: {blackListWords ? 'Yes' : 'No'}
{blackListWords && (
Filtering {blackListWords.length} words
)}
);
};
```
--------------------------------
### Test Encryption Status with FirestoreServices
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
Retrieves and logs the encryption status from FirestoreServices. It checks if encryption is enabled, ready, if a key has been generated, and if tests have passed. Logs an error if encryption is not working correctly.
```javascript
// Test encryption setup
async function testEncryptionStatus() {
const status = await firestoreService.getEncryptionStatus();
console.log('Encryption enabled:', status.isEnabled);
console.log('Encryption ready:', status.isReady);
console.log('Encryption key generated:', status.keyGenerated);
console.log('Encryption test passed:', status.testPassed);
console.log('Last tested:', status.lastTestedAt);
if (!status.testPassed) {
console.error('Encryption is not working properly!');
}
}
```
--------------------------------
### Load Message History with Pagination using FirestoreServices
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
Loads message history from FirestoreServices with pagination support. It allows specifying a page size and fetching subsequent pages using `getMoreMessage`. Returns an array of messages or an empty array if an error occurs.
```javascript
// Get message history with pagination
async function loadMessageHistory(pageSize = 20) {
try {
const messages = await firestoreService.getMessageHistory(pageSize);
console.log(`Loaded ${messages.length} messages`);
// Load more messages
const moreMessages = await firestoreService.getMoreMessage(pageSize);
console.log(`Loaded ${moreMessages.length} more messages`);
return [...messages, ...moreMessages];
} catch (error) {
console.error('Error loading messages:', error);
return [];
}
}
```
--------------------------------
### Custom Encryption Functions using CryptoJS
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
Implements custom encryption and decryption functions using the CryptoJS library. These functions can be passed to the ChatProvider to override the default AES encryption, allowing for custom key derivation, encryption, and decryption logic. Requires CryptoJS as a dependency.
```javascript
import React from 'react';
import { ChatProvider } from 'rn-firebase-chat';
import CryptoJS from 'crypto-js';
// Custom encryption using CryptoJS
const customEncryptionFunctions = {
generateKeyFunctionProp: async (key) => {
// Custom key derivation
const salt = CryptoJS.lib.WordArray.random(128 / 8);
const derivedKey = CryptoJS.PBKDF2(key, salt, {
keySize: 256 / 32,
iterations: 10000,
});
return derivedKey.toString();
},
encryptFunctionProp: async (text) => {
// Custom encryption logic
const encrypted = CryptoJS.AES.encrypt(text, 'secret-key').toString();
return encrypted;
},
decryptFunctionProp: async (ciphertext) => {
// Custom decryption logic
const bytes = CryptoJS.AES.decrypt(ciphertext, 'secret-key');
const decrypted = bytes.toString(CryptoJS.enc.Utf8);
return decrypted;
},
};
export const AppWithCustomEncryption = () => {
const userInfo = {
id: 'user_crypto_001',
name: 'Crypto User',
avatar: 'https://example.com/crypto.jpg',
};
const encryptionOptions = {
salt: 'custom-salt-for-encryption',
iterations: 10000,
keyLength: 256,
};
return (
);
};
// Using built-in AES encryption
export const AppWithBuiltInEncryption = () => {
const userInfo = {
id: 'user_secure_001',
name: 'Secure User',
avatar: 'https://example.com/secure.jpg',
};
return (
);
};
```
--------------------------------
### Create Conversation Programmatically with FirestoreServices
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
Programmatically creates a new conversation using FirestoreServices. It allows specifying member IDs, conversation name, image, and group status. The function returns the created conversation object, including its ID.
```javascript
// Create a conversation programmatically
async function createConversationManually() {
const memberIds = ['user_001', 'user_002'];
const conversationName = 'Direct Chat';
const conversationImage = 'https://example.com/chat-icon.jpg';
const isGroup = false;
const conversation = await firestoreService.createConversation(
'', // Auto-generate ID
memberIds,
conversationName,
conversationImage,
isGroup
);
console.log('Created conversation:', conversation.id);
return conversation;
}
```
--------------------------------
### TypeScript Message and Conversation Interfaces
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
Defines TypeScript interfaces for message and conversation types used in rn-firebase-chat. These interfaces ensure type safety when creating, manipulating, and handling chat data, including message content, sender information, timestamps, and media types.
```typescript
import type {
MessageProps,
ConversationProps,
IUserInfo,
MediaType,
MessageStatus,
} from 'rn-firebase-chat';
// Create a typed message
const newMessage: MessageProps = {
id: 'msg_001',
text: 'Hello, how are you?',
senderId: 'user_001',
createdAt: Date.now(),
readBy: {
'user_001': true,
'user_002': false,
},
status: MessageStatus.sent,
type: 'text',
user: {
_id: 'user_001',
name: 'John Doe',
avatar: 'https://example.com/john.jpg',
},
};
// Create a media message
const imageMessage: MessageProps = {
id: 'msg_002',
text: '',
senderId: 'user_001',
createdAt: Date.now(),
readBy: { 'user_001': true },
type: 'image',
path: 'https://storage.firebase.com/image.jpg',
extension: 'jpg',
image: 'https://storage.firebase.com/image.jpg',
user: {
_id: 'user_001',
name: 'John Doe',
},
};
// Type-safe conversation handler
function handleConversation(conversation: ConversationProps) {
console.log('Conversation ID:', conversation.id);
console.log('Members:', conversation.members);
console.log('Latest message:', conversation.latestMessage?.text);
console.log('Unread count:', conversation.unRead);
console.log('Updated at:', new Date(conversation.updatedAt));
// Check typing status
if (conversation.typing) {
const typingUsers = Object.entries(conversation.typing)
.filter(([_, isTyping]) => isTyping)
.map(([userId]) => userId);
console.log('Users typing:', typingUsers);
}
}
// Type-safe user info
const userInfo: IUserInfo = {
id: 'user_123',
name: 'Jane Smith',
avatar: 'https://example.com/jane.jpg',
};
// Media type handling
function getMediaIcon(type: MediaType): string {
switch (type) {
case 'image':
return '📷';
case 'video':
return '🎥';
case 'text':
default:
return '💬';
}
}
```
--------------------------------
### Select Specific Chat State with useChatSelector (React Native)
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
The `useChatSelector` hook enables selective access to specific parts of the chat state, optimizing re-renders by subscribing only to necessary data. It takes a selector function as an argument. Dependencies include 'react' and 'rn-firebase-chat'.
```javascript
import React from 'react';
import { View, Text, FlatList } from 'react-native';
import { useChatSelector, setConversation } from 'rn-firebase-chat';
import { getListConversation, getConversation } from 'rn-firebase-chat/src/reducer/selectors';
// Display conversation count
export const ConversationCounter = () => {
const conversations = useChatSelector(getListConversation);
return (
You have {conversations?.length || 0} conversations
);
};
// Display current active conversation
export const CurrentConversationInfo = () => {
const conversation = useChatSelector(getConversation);
if (!conversation) {
return No active conversation;
}
return (
Conversation: {conversation.name || 'Unknown'}Members: {conversation.members?.length || 0}Latest: {conversation.latestMessage?.text || 'No messages'}
);
};
// List all conversations with unread counts
export const UnreadConversationsList = () => {
const conversations = useChatSelector(getListConversation);
const unreadConversations = conversations?.filter(conv => conv.unRead > 0) || [];
return (
item.id}
renderItem={({ item }) => (
{item.name || 'Unknown'}
{item.unRead} unread messages
)}
/>
);
};
```
--------------------------------
### Display Conversation List with ListConversationScreen in React Native
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
The ListConversationScreen component displays a list of user conversations, showing the latest message, timestamp, and unread count. It supports navigation to individual chat screens and allows for custom rendering of conversation items.
```javascript
import React, { useCallback } from 'react';
import { ListConversationScreen } from 'rn-firebase-chat';
import { useNavigation } from '@react-navigation/native';
export const ConversationsListScreen = () => {
const navigation = useNavigation();
const handleConversationPress = useCallback((conversation) => {
// Navigate to chat screen with conversation data
navigation.navigate('ChatScreen', {
conversationId: conversation.id,
memberIds: conversation.members,
partners: conversation.partners,
});
}, [navigation]);
return (
);
};
// Custom conversation item rendering
export const CustomConversationsScreen = () => {
const navigation = useNavigation();
const renderCustomItem = useCallback(({ item, index }) => {
return (
{item.name || 'Unknown'}{item.latestMessage?.text || 'No messages'}Unread: {item.unRead || 0}
);
}, []);
return (
navigation.navigate('ChatScreen', conv)}
renderCustomItem={renderCustomItem}
/>
);
};
```
--------------------------------
### Send Custom Message with FirestoreServices
Source: https://context7.com/saigontechnology/rn-firebase-chat/llms.txt
Sends a custom message through FirestoreServices. This function takes a message object containing text, sender ID, read receipts, creation timestamp, and type. It confirms the message has been sent.
```javascript
// Send a message programmatically
async function sendCustomMessage() {
const messageData = {
text: 'Hello from custom code!',
senderId: 'user_001',
readBy: { 'user_001': true },
createdAt: Date.now(),
type: 'text',
};
await firestoreService.sendMessage(messageData);
console.log('Message sent');
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.