Last active
March 1, 2021 09:33
-
-
Save vishalnarkhede/70fe2a544fbf3db74fdc6bbfe95efc6e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useEffect, useState} from 'react'; | |
import {SafeAreaView, StyleSheet, Text, View} from 'react-native'; | |
import {FlatList} from 'react-native-bidirectional-infinite-scroll'; | |
import {MessageBubble} from './MessageBubble'; | |
import {queryMoreMessages} from './utils'; | |
const App = () => { | |
const [messages, setMessages] = useState(); | |
useEffect(() => { | |
// When app is opened, we are going to render 50 messages on screen. | |
// Generally this is where you connect to chat server and query first batch of messages. | |
const initChat = async () => { | |
const initialMessages = await queryMoreMessages(50, 0); | |
setMessages(initialMessages); | |
}; | |
initChat(); | |
}, []); | |
// Add 10 more messages to end of the list. | |
// In real chat application, this is where you have your pagination logic. | |
const loadMoreOlderMessages = async () => { | |
const newMessages = await queryMoreMessages(10); | |
setMessages((m) => { | |
return m.concat(newMessages); | |
}); | |
}; | |
// Add 10 more messages to beginning of the list. | |
// In real chat application, this is where you have your pagination logic. | |
const loadMoreRecentMessages = async () => { | |
const newMessages = await queryMoreMessages(10); | |
setMessages((m) => { | |
return newMessages.concat(m); | |
}); | |
}; | |
if (!messages) { | |
// If the messages are not ready, lets not show anything. | |
// Generally you can render some kind of loading indicator in this case. | |
return null; | |
} | |
/** | |
* NOTE: | |
* | |
* - You can also control the scroll offset, at which `onEndReached` and `onStartReached` | |
* should be called, using props - onEndReachedThreshold and onStartReachedThrehols | |
* - We are using `inverted` FlatList, since thats a common UX for Chat applications. | |
*/ | |
return ( | |
<SafeAreaView style={styles.safeArea}> | |
<View style={styles.header}> | |
<Text style={styles.headerTitle}>Chat between two users</Text> | |
</View> | |
<FlatList | |
data={messages} | |
inverted | |
onEndReached={loadMoreOlderMessages} | |
onStartReached={loadMoreRecentMessages} | |
renderItem={MessageBubble} | |
/> | |
</SafeAreaView> | |
); | |
}; | |
const styles = StyleSheet.create({ | |
header: { | |
alignItems: 'center', | |
paddingVertical: 10, | |
borderBottomColor: '#BEBEBE', | |
borderBottomWidth: 1, | |
}, | |
headerTitle: {fontSize: 20, fontWeight: 'bold'}, | |
safeArea: { | |
flex: 1, | |
}, | |
}); | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment