From b967bd77710bce7b92ae0863df52cce345abd4e4 Mon Sep 17 00:00:00 2001 From: Shravya Ramesh Date: Fri, 9 Apr 2021 12:20:25 -0700 Subject: connecting user during login --- src/screens/chat/ChatListScreen.tsx | 28 +++++++--------------- src/screens/onboarding/CategorySelection.tsx | 6 +++-- .../onboarding/InvitationCodeVerification.tsx | 6 +++-- src/screens/onboarding/Login.tsx | 6 +++-- 4 files changed, 21 insertions(+), 25 deletions(-) (limited to 'src/screens') diff --git a/src/screens/chat/ChatListScreen.tsx b/src/screens/chat/ChatListScreen.tsx index 3290116b..dbdb7994 100644 --- a/src/screens/chat/ChatListScreen.tsx +++ b/src/screens/chat/ChatListScreen.tsx @@ -1,8 +1,8 @@ import AsyncStorage from '@react-native-community/async-storage'; import {StackNavigationProp} from '@react-navigation/stack'; import React, {useContext, useEffect, useMemo, useState} from 'react'; -import {SafeAreaView, StatusBar, StyleSheet, View} from 'react-native'; -import {useStore} from 'react-redux'; +import {Alert, SafeAreaView, StatusBar, StyleSheet, View} from 'react-native'; +import {useSelector, useStore} from 'react-redux'; import {ChannelList, Chat} from 'stream-chat-react-native'; import {ChatContext} from '../../App'; import {TabsGradient} from '../../components'; @@ -31,7 +31,9 @@ interface ChatListScreenProps { */ const ChatListScreen: React.FC = () => { const {chatClient} = useContext(ChatContext); - const [clientReady, setClientReady] = useState(false); + const chatClientReady = useSelector( + (state: RootState) => state.user.chatClientReady, + ); const state: RootState = useStore().getState(); const loggedInUserId = state.user.user.userId; @@ -44,22 +46,10 @@ const ChatListScreen: React.FC = () => { ); useEffect(() => { - const setupClient = async () => { - const chatToken = await AsyncStorage.getItem('chatToken'); - await chatClient.connectUser( - { - id: loggedInUserId, - }, - chatToken, - ); - return setClientReady(true); - }; - if (!clientReady) { - setupClient().catch((err) => { - console.error(err); - }); + if (!chatClientReady) { + Alert.alert('Something wrong with chat'); } - }, []); + }, [chatClientReady]); return ( @@ -75,7 +65,7 @@ const ChatListScreen: React.FC = () => { channel.create(); }} /> - {clientReady && ( + {chatClientReady && ( = ({ * Same component to be used for category selection while onboarding and while on profile */ const {screenType, user} = route.params; + const {chatClient} = useContext(ChatContext); const isOnBoarding: boolean = screenType === CategorySelectionScreenType.Onboarding; const {userId, username} = user; @@ -168,7 +170,7 @@ const CategorySelection: React.FC = ({ dispatch(updateIsOnboardedUser(true)); const token = await getTokenOrLogout(dispatch); await postMomentCategories(selectedCategories, token); - userLogin(dispatch, {userId: userId, username: username}); + userLogin(dispatch, {userId: userId, username: username}, chatClient); } else { dispatch( updateMomentCategories( diff --git a/src/screens/onboarding/InvitationCodeVerification.tsx b/src/screens/onboarding/InvitationCodeVerification.tsx index e160b4b7..774a7a11 100644 --- a/src/screens/onboarding/InvitationCodeVerification.tsx +++ b/src/screens/onboarding/InvitationCodeVerification.tsx @@ -1,7 +1,7 @@ import AsyncStorage from '@react-native-community/async-storage'; import {RouteProp} from '@react-navigation/native'; import {StackNavigationProp} from '@react-navigation/stack'; -import React from 'react'; +import React, {useContext} from 'react'; import {Alert, KeyboardAvoidingView, StyleSheet, View} from 'react-native'; import {Text} from 'react-native-animatable'; import { @@ -27,6 +27,7 @@ import { import {OnboardingStackParams} from '../../routes'; import {BackgroundGradientType} from '../../types'; import {SCREEN_WIDTH, userLogin} from '../../utils'; +import {ChatContext} from '../../App'; type InvitationCodeVerificationRouteProp = RouteProp< OnboardingStackParams, @@ -58,6 +59,7 @@ const InvitationCodeVerification: React.FC = ({ setValue, }); const dispatch = useDispatch(); + const {chatClient} = useContext(ChatContext); const handleInvitationCodeVerification = async () => { if (value.length === 6) { @@ -77,7 +79,7 @@ const InvitationCodeVerification: React.FC = ({ const username = route.params.username; await AsyncStorage.setItem('userId', userId); await AsyncStorage.setItem('username', username); - userLogin(dispatch, {userId, username}); + userLogin(dispatch, {userId, username}, chatClient); } else { Alert.alert(ERROR_INVALID_INVITATION_CODE); } diff --git a/src/screens/onboarding/Login.tsx b/src/screens/onboarding/Login.tsx index dd2bb2e4..4f2b6a64 100644 --- a/src/screens/onboarding/Login.tsx +++ b/src/screens/onboarding/Login.tsx @@ -1,7 +1,7 @@ import AsyncStorage from '@react-native-community/async-storage'; import {RouteProp} from '@react-navigation/native'; import {StackNavigationProp} from '@react-navigation/stack'; -import React, {useEffect, useRef} from 'react'; +import React, {useContext, useEffect, useRef} from 'react'; import { Alert, Image, @@ -14,6 +14,7 @@ import { } from 'react-native'; import SplashScreen from 'react-native-splash-screen'; import {useDispatch, useSelector} from 'react-redux'; +import {ChatContext} from '../../App'; import {Background, TaggInput, TaggSquareButton} from '../../components'; import {LOGIN_ENDPOINT, usernameRegex} from '../../constants'; import { @@ -47,6 +48,7 @@ interface LoginProps { const Login: React.FC = ({navigation}: LoginProps) => { // ref for focusing on input fields const inputRef = useRef(); + const {chatClient} = useContext(ChatContext); // login form state const [form, setForm] = React.useState({ @@ -166,7 +168,7 @@ const Login: React.FC = ({navigation}: LoginProps) => { if (statusCode === 200 && data.isOnboarded) { //Stores token received in the response into client's AsynStorage try { - userLogin(dispatch, {userId: data.UserID, username}); + userLogin(dispatch, {userId: data.UserID, username}, chatClient); fcmService.sendFcmTokenToServer(); } catch (err) { Alert.alert(ERROR_INVALID_LOGIN); -- cgit v1.2.3-70-g09d2 From bdd1ed17600da7b766e2b0fa97ad4cbf01234819 Mon Sep 17 00:00:00 2001 From: Shravya Ramesh Date: Fri, 9 Apr 2021 13:46:42 -0700 Subject: removed client ready from redux --- src/components/profile/ProfileBody.tsx | 6 ++-- src/routes/Routes.tsx | 2 +- src/screens/chat/ChatListScreen.tsx | 51 +++++++++++++++------------------- src/store/actions/user.ts | 15 ---------- src/store/initialStates.ts | 1 - src/utils/messages.ts | 4 +-- 6 files changed, 28 insertions(+), 51 deletions(-) (limited to 'src/screens') diff --git a/src/components/profile/ProfileBody.tsx b/src/components/profile/ProfileBody.tsx index dc68446b..e23249fa 100644 --- a/src/components/profile/ProfileBody.tsx +++ b/src/components/profile/ProfileBody.tsx @@ -63,7 +63,6 @@ const ProfileBody: React.FC = ({ profile, ); - const {chatClientReady} = useSelector((state: RootState) => state.user); const {chatClient, setChannel} = useContext(ChatContext); const state: RootState = useStore().getState(); @@ -97,8 +96,9 @@ const ProfileBody: React.FC = ({ }; const onPressMessage = async () => { - if (!chatClientReady) { - Alert.alert('Something wrong with chat'); + if (!chatClient.user) { + // TODO: Add refresh control to retry establishing chat connection + Alert.alert('Unable to connect chat'); } const channel = chatClient.channel('messaging', { members: [loggedInUserId, String(userXId)], diff --git a/src/routes/Routes.tsx b/src/routes/Routes.tsx index 173a6a6c..adc6253b 100644 --- a/src/routes/Routes.tsx +++ b/src/routes/Routes.tsx @@ -54,7 +54,7 @@ const Routes: React.FC = () => { if (userId) { fcmService.setUpPushNotifications(); fcmService.sendFcmTokenToServer(); - connectChatAccount(loggedInUserId, chatClient, dispatch); + connectChatAccount(loggedInUserId, chatClient); } }, []); diff --git a/src/screens/chat/ChatListScreen.tsx b/src/screens/chat/ChatListScreen.tsx index dbdb7994..eb886232 100644 --- a/src/screens/chat/ChatListScreen.tsx +++ b/src/screens/chat/ChatListScreen.tsx @@ -31,9 +31,6 @@ interface ChatListScreenProps { */ const ChatListScreen: React.FC = () => { const {chatClient} = useContext(ChatContext); - const chatClientReady = useSelector( - (state: RootState) => state.user.chatClientReady, - ); const state: RootState = useStore().getState(); const loggedInUserId = state.user.user.userId; @@ -65,31 +62,29 @@ const ChatListScreen: React.FC = () => { channel.create(); }} /> - {chatClientReady && ( - - - - filters={memoizedFilters} - options={{ - presence: true, - state: true, - watch: true, - }} - sort={{last_message_at: -1}} - maxUnreadCount={99} - Preview={ChannelPreview} - /> - - - )} + + + + filters={memoizedFilters} + options={{ + presence: true, + state: true, + watch: true, + }} + sort={{last_message_at: -1}} + maxUnreadCount={99} + Preview={ChannelPreview} + /> + + diff --git a/src/store/actions/user.ts b/src/store/actions/user.ts index 0ed57fe6..c7d0d5a7 100644 --- a/src/store/actions/user.ts +++ b/src/store/actions/user.ts @@ -11,7 +11,6 @@ import {getTokenOrLogout} from '../../utils'; import { clearHeaderAndProfileImages, profileCompletionStageUpdated, - setChatClientReady, setIsOnboardedUser, setNewNotificationReceived, setNewVersionAvailable, @@ -235,17 +234,3 @@ export const suggestedPeopleAnimatedTutorialFinished = ( } }; -export const updateChatClientReady = ( - chatClientReady: boolean, -): ThunkAction, RootState, unknown, Action> => async ( - dispatch, -) => { - try { - dispatch({ - type: setChatClientReady.type, - payload: {chatClientReady}, - }); - } catch (error) { - console.log(error); - } -}; diff --git a/src/store/initialStates.ts b/src/store/initialStates.ts index 546c57a9..02331eb6 100644 --- a/src/store/initialStates.ts +++ b/src/store/initialStates.ts @@ -41,7 +41,6 @@ export const EMPTY_PROFILE_PREVIEW_LIST = []; export const NO_USER_DATA = { user: NO_USER, - chatClientReady: false, profile: NO_PROFILE, avatar: undefined, cover: undefined, diff --git a/src/utils/messages.ts b/src/utils/messages.ts index b2162d34..1c83ca9f 100644 --- a/src/utils/messages.ts +++ b/src/utils/messages.ts @@ -1,6 +1,6 @@ import AsyncStorage from '@react-native-community/async-storage'; import moment from 'moment'; -import {updateChatClientReady} from '../store/actions'; +// import {updateChatClientReady} from '../store/actions'; import {AppDispatch} from '../store/configureStore'; import {RootState} from '../store/rootReducer'; import {ChannelGroupedType} from '../types'; @@ -98,9 +98,7 @@ export const connectChatAccount = async ( }, chatToken, ); - dispatch(updateChatClientReady(true)); } catch (err) { - dispatch(updateChatClientReady(false)); console.log('Error while connecting user to Stream: ', err); } }; -- cgit v1.2.3-70-g09d2 From 45041863a432ed5ba02f896f0c4f3c23ae7830ed Mon Sep 17 00:00:00 2001 From: Shravya Ramesh Date: Fri, 9 Apr 2021 14:37:06 -0700 Subject: removed chat client inside userlogin --- src/components/profile/Content.tsx | 2 +- src/screens/onboarding/CategorySelection.tsx | 2 +- src/screens/onboarding/InvitationCodeVerification.tsx | 2 +- src/store/reducers/userReducer.ts | 5 +---- src/utils/users.ts | 10 +--------- 5 files changed, 5 insertions(+), 16 deletions(-) (limited to 'src/screens') diff --git a/src/components/profile/Content.tsx b/src/components/profile/Content.tsx index 0d2a0331..0052b61d 100644 --- a/src/components/profile/Content.tsx +++ b/src/components/profile/Content.tsx @@ -84,7 +84,7 @@ const Content: React.FC = ({userXId, screenType}) => { const refrestState = async () => { setRefreshing(true); if (!userXId) { - await userLogin(dispatch, loggedInUser, chatClient); + await userLogin(dispatch, loggedInUser); } else { await fetchUserX(dispatch, user, screenType); } diff --git a/src/screens/onboarding/CategorySelection.tsx b/src/screens/onboarding/CategorySelection.tsx index 1407575c..ab5ff3be 100644 --- a/src/screens/onboarding/CategorySelection.tsx +++ b/src/screens/onboarding/CategorySelection.tsx @@ -170,7 +170,7 @@ const CategorySelection: React.FC = ({ dispatch(updateIsOnboardedUser(true)); const token = await getTokenOrLogout(dispatch); await postMomentCategories(selectedCategories, token); - userLogin(dispatch, {userId: userId, username: username}, chatClient); + userLogin(dispatch, {userId: userId, username: username}); } else { dispatch( updateMomentCategories( diff --git a/src/screens/onboarding/InvitationCodeVerification.tsx b/src/screens/onboarding/InvitationCodeVerification.tsx index 774a7a11..6bc0ac9d 100644 --- a/src/screens/onboarding/InvitationCodeVerification.tsx +++ b/src/screens/onboarding/InvitationCodeVerification.tsx @@ -79,7 +79,7 @@ const InvitationCodeVerification: React.FC = ({ const username = route.params.username; await AsyncStorage.setItem('userId', userId); await AsyncStorage.setItem('username', username); - userLogin(dispatch, {userId, username}, chatClient); + userLogin(dispatch, {userId, username}); } else { Alert.alert(ERROR_INVALID_INVITATION_CODE); } diff --git a/src/store/reducers/userReducer.ts b/src/store/reducers/userReducer.ts index 0b958cac..a8789c1d 100644 --- a/src/store/reducers/userReducer.ts +++ b/src/store/reducers/userReducer.ts @@ -75,9 +75,6 @@ const userDataSlice = createSlice({ state.avatar = ''; state.cover = ''; }, - setChatClientReady: (state, action) => { - state.chatClientReady = action.payload.chatClientReady; - }, }, }); @@ -93,6 +90,6 @@ export const { setReplyPosted, setSuggestedPeopleImage, clearHeaderAndProfileImages, - setChatClientReady, + // setChatClientReady, } = userDataSlice.actions; export const userDataReducer = userDataSlice.reducer; diff --git a/src/utils/users.ts b/src/utils/users.ts index ec09198d..7148eb79 100644 --- a/src/utils/users.ts +++ b/src/utils/users.ts @@ -22,7 +22,6 @@ import { ScreenType, UserType, } from './../types/types'; -import {connectChatAccount} from './messages'; const loadData = async (dispatch: AppDispatch, user: UserType) => { await Promise.all([ @@ -43,11 +42,7 @@ const loadData = async (dispatch: AppDispatch, user: UserType) => { * @param dispatch This is the dispatch object from the redux store * @param user The user if at all any */ -export const userLogin = async ( - dispatch: AppDispatch, - user: UserType, - chatClient?, -) => { +export const userLogin = async (dispatch: AppDispatch, user: UserType) => { try { let localUser = {...user}; if (!user.userId) { @@ -67,9 +62,6 @@ export const userLogin = async ( AsyncStorage.setItem('username', user.username), ]); } - if (chatClient) { - connectChatAccount(localUser.userId, chatClient, dispatch); - } await loadData(dispatch, localUser); } catch (error) { console.log(error); -- cgit v1.2.3-70-g09d2 From 3d26676ea1e818b585b4b224f643524994a0e893 Mon Sep 17 00:00:00 2001 From: Shravya Ramesh Date: Fri, 9 Apr 2021 14:40:03 -0700 Subject: Connecting during login, app entry, msg btn tap --- src/components/profile/ProfileBody.tsx | 23 ++++++++++++++--------- src/routes/Routes.tsx | 5 ++++- src/screens/onboarding/Login.tsx | 6 +++--- 3 files changed, 21 insertions(+), 13 deletions(-) (limited to 'src/screens') diff --git a/src/components/profile/ProfileBody.tsx b/src/components/profile/ProfileBody.tsx index e23249fa..eebdb167 100644 --- a/src/components/profile/ProfileBody.tsx +++ b/src/components/profile/ProfileBody.tsx @@ -21,6 +21,7 @@ import {NO_PROFILE} from '../../store/initialStates'; import {RootState} from '../../store/rootReducer'; import {ScreenType} from '../../types'; import { + connectChatAccount, getUserAsProfilePreviewType, SCREEN_HEIGHT, SCREEN_WIDTH, @@ -96,16 +97,20 @@ const ProfileBody: React.FC = ({ }; const onPressMessage = async () => { - if (!chatClient.user) { - // TODO: Add refresh control to retry establishing chat connection - Alert.alert('Unable to connect chat'); + let connected: boolean = !chatClient.user; + if (!connected) { + connected = await connectChatAccount(loggedInUserId, chatClient); + if (!connected) { + Alert.alert('Unable to connect chat'); + } + } else { + const channel = chatClient.channel('messaging', { + members: [loggedInUserId, String(userXId)], + }); + channel.create(); + setChannel(channel); + navigation.navigate('Chat'); } - const channel = chatClient.channel('messaging', { - members: [loggedInUserId, String(userXId)], - }); - channel.create(); - setChannel(channel); - navigation.navigate('Chat'); }; return ( diff --git a/src/routes/Routes.tsx b/src/routes/Routes.tsx index adc6253b..5ce0c771 100644 --- a/src/routes/Routes.tsx +++ b/src/routes/Routes.tsx @@ -54,10 +54,13 @@ const Routes: React.FC = () => { if (userId) { fcmService.setUpPushNotifications(); fcmService.sendFcmTokenToServer(); - connectChatAccount(loggedInUserId, chatClient); } }, []); + useEffect(() => { + connectChatAccount(loggedInUserId, chatClient); + }, [loggedInUserId]); + useEffect(() => { const checkVersion = async () => { const liveVersions = await getCurrentLiveVersions(); diff --git a/src/screens/onboarding/Login.tsx b/src/screens/onboarding/Login.tsx index 4f2b6a64..6d9abf82 100644 --- a/src/screens/onboarding/Login.tsx +++ b/src/screens/onboarding/Login.tsx @@ -29,7 +29,7 @@ import {OnboardingStackParams} from '../../routes/onboarding'; import {fcmService} from '../../services'; import {RootState} from '../../store/rootReducer'; import {BackgroundGradientType, UniversityType} from '../../types'; -import {normalize, userLogin} from '../../utils'; +import {connectChatAccount, normalize, userLogin} from '../../utils'; import UpdateRequired from './UpdateRequired'; type VerificationScreenRouteProp = RouteProp; @@ -162,14 +162,14 @@ const Login: React.FC = ({navigation}: LoginProps) => { await AsyncStorage.setItem('token', data.token); await AsyncStorage.setItem('userId', data.UserID); await AsyncStorage.setItem('username', username); - await AsyncStorage.setItem('chatToken', data.chatToken); } if (statusCode === 200 && data.isOnboarded) { //Stores token received in the response into client's AsynStorage try { - userLogin(dispatch, {userId: data.UserID, username}, chatClient); + userLogin(dispatch, {userId: data.UserID, username}); fcmService.sendFcmTokenToServer(); + connectChatAccount(data.UserID, chatClient); } catch (err) { Alert.alert(ERROR_INVALID_LOGIN); } -- cgit v1.2.3-70-g09d2 From 6527289eb6249cfd057c47d0f797133ab8052339 Mon Sep 17 00:00:00 2001 From: Shravya Ramesh Date: Fri, 9 Apr 2021 15:19:49 -0700 Subject: major issue fixed --- src/screens/chat/ChatListScreen.tsx | 17 ++++++++++++++--- src/services/ChatService.ts | 6 +++--- src/utils/messages.ts | 5 +++-- 3 files changed, 20 insertions(+), 8 deletions(-) (limited to 'src/screens') diff --git a/src/screens/chat/ChatListScreen.tsx b/src/screens/chat/ChatListScreen.tsx index eb886232..f2395f0a 100644 --- a/src/screens/chat/ChatListScreen.tsx +++ b/src/screens/chat/ChatListScreen.tsx @@ -3,6 +3,7 @@ import {StackNavigationProp} from '@react-navigation/stack'; import React, {useContext, useEffect, useMemo, useState} from 'react'; import {Alert, SafeAreaView, StatusBar, StyleSheet, View} from 'react-native'; import {useSelector, useStore} from 'react-redux'; +import {connectChatAccount} from '../../utils'; import {ChannelList, Chat} from 'stream-chat-react-native'; import {ChatContext} from '../../App'; import {TabsGradient} from '../../components'; @@ -43,10 +44,20 @@ const ChatListScreen: React.FC = () => { ); useEffect(() => { - if (!chatClientReady) { - Alert.alert('Something wrong with chat'); + let connected: boolean = !chatClient.user; + if (!connected) { + connectChatAccount(loggedInUserId, chatClient) + .then((success) => { + if (!success) { + Alert.alert('Something wrong with chat'); + } + }) + .catch((err) => { + console.log('Error connecting to chat: ', err); + Alert.alert('Something wrong with chat'); + }); } - }, [chatClientReady]); + }, []); return ( diff --git a/src/services/ChatService.ts b/src/services/ChatService.ts index da65641c..e9b1c284 100644 --- a/src/services/ChatService.ts +++ b/src/services/ChatService.ts @@ -3,7 +3,7 @@ import {CHAT_TOKEN_ENDPOINT} from '../constants/api'; export const loadChatTokenService = async () => { try { - const token = await AsyncStorage.getItem('chatToken'); + const token = await AsyncStorage.getItem('token'); const response = await fetch(CHAT_TOKEN_ENDPOINT, { method: 'GET', headers: { @@ -12,8 +12,8 @@ export const loadChatTokenService = async () => { }); const status = response.status; if (status === 200) { - const {chatToken} = await response.json(); - return chatToken; + const data = await response.json(); + return data.chatToken; } return ''; } catch (error) { diff --git a/src/utils/messages.ts b/src/utils/messages.ts index 6b972b83..dc01d579 100644 --- a/src/utils/messages.ts +++ b/src/utils/messages.ts @@ -111,9 +111,10 @@ export const connectChatAccount = async ( export const getChatToken = async () => { try { - if (await AsyncStorage.getItem('chatToken')) { + const currentChatToken = await AsyncStorage.getItem('chatToken'); + if (currentChatToken === null) { const chatToken = await loadChatTokenService(); - AsyncStorage.setItem('chatToken', chatToken); + await AsyncStorage.setItem('chatToken', chatToken); } } catch (err) { console.log(err); -- cgit v1.2.3-70-g09d2 From 61034f314712750225ba21f1763014f26953479a Mon Sep 17 00:00:00 2001 From: Shravya Ramesh Date: Fri, 9 Apr 2021 16:16:36 -0700 Subject: remove redundant if --- src/screens/chat/ChatListScreen.tsx | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) (limited to 'src/screens') diff --git a/src/screens/chat/ChatListScreen.tsx b/src/screens/chat/ChatListScreen.tsx index a019891a..f9db0c77 100644 --- a/src/screens/chat/ChatListScreen.tsx +++ b/src/screens/chat/ChatListScreen.tsx @@ -45,19 +45,16 @@ const ChatListScreen: React.FC = () => { ); useEffect(() => { - let connected: boolean = !chatClient.user; - if (!connected) { - connectChatAccount(loggedInUserId, chatClient) - .then((success) => { - if (!success) { - Alert.alert('Something wrong with chat'); - } - }) - .catch((err) => { - console.log('Error connecting to chat: ', err); + connectChatAccount(loggedInUserId, chatClient) + .then((success) => { + if (!success) { Alert.alert('Something wrong with chat'); - }); - } + } + }) + .catch((err) => { + console.log('Error connecting to chat: ', err); + Alert.alert('Something wrong with chat'); + }); }, []); return ( -- cgit v1.2.3-70-g09d2 From ad9db5ffd0b2fb6334fd8237e0600a76d25c7053 Mon Sep 17 00:00:00 2001 From: Ivan Chen Date: Fri, 9 Apr 2021 19:22:30 -0400 Subject: added navigation to profile --- src/components/messages/ChatHeader.tsx | 81 ++++++++++++++++++++++++---------- src/components/profile/ProfileBody.tsx | 16 +++---- src/constants/strings.ts | 3 +- src/screens/chat/ChatScreen.tsx | 3 +- src/store/initialStates.ts | 1 + 5 files changed, 69 insertions(+), 35 deletions(-) (limited to 'src/screens') diff --git a/src/components/messages/ChatHeader.tsx b/src/components/messages/ChatHeader.tsx index 2bc096ec..67a7f1fe 100644 --- a/src/components/messages/ChatHeader.tsx +++ b/src/components/messages/ChatHeader.tsx @@ -1,39 +1,71 @@ +import {useNavigation} from '@react-navigation/native'; import React, {useContext} from 'react'; import {Image, StyleSheet, View} from 'react-native'; import {Text} from 'react-native-animatable'; -import {useStore} from 'react-redux'; +import {TouchableOpacity} from 'react-native-gesture-handler'; +import {useDispatch, useStore} from 'react-redux'; import {ChatContext} from '../../App'; -import {ChatHeaderHeight, normalize, StatusBarHeight} from '../../utils'; +import {ScreenType} from '../../types'; +import { + ChatHeaderHeight, + fetchUserX, + normalize, + StatusBarHeight, + userXInStore, +} from '../../utils'; import {formatLastSeenText, getMember, isOnline} from '../../utils/messages'; -type ChatHeaderProps = {}; +type ChatHeaderProps = { + screenType: ScreenType; +}; -const ChatHeader: React.FC = () => { +const ChatHeader: React.FC = (props) => { + const {screenType} = props; const {channel} = useContext(ChatContext); + const dispatch = useDispatch(); + const navigation = useNavigation(); const state = useStore().getState(); const member = getMember(channel, state); const online = isOnline(member?.user?.last_active); const lastSeen = formatLastSeenText(member?.user?.last_active); + const toProfile = async () => { + if (member && member.user && member.user.username) { + if (!userXInStore(state, screenType, member.user.id)) { + await fetchUserX( + dispatch, + {userId: member.user.id, username: member.user.username}, + screenType, + ); + } + navigation.navigate('Profile', { + userXId: member.user.id, + screenType, + }); + } + }; + return ( - - - {online && } - - - - {member?.user?.first_name} {member?.user?.last_name} - - {lastSeen} - + + + + {online && } + + + + {member?.user?.first_name} {member?.user?.last_name} + + {lastSeen} + + ); }; @@ -41,10 +73,13 @@ const ChatHeader: React.FC = () => { const styles = StyleSheet.create({ container: { height: ChatHeaderHeight - StatusBarHeight, - flexDirection: 'row', - alignItems: 'center', paddingLeft: '15%', }, + tappables: { + alignItems: 'center', + flexDirection: 'row', + width: '100%', + }, avatar: { width: normalize(40), height: normalize(40), diff --git a/src/components/profile/ProfileBody.tsx b/src/components/profile/ProfileBody.tsx index 00532507..527036f6 100644 --- a/src/components/profile/ProfileBody.tsx +++ b/src/components/profile/ProfileBody.tsx @@ -22,6 +22,7 @@ import {RootState} from '../../store/rootReducer'; import {ScreenType} from '../../types'; import { connectChatAccount, + createChannel, getUserAsProfilePreviewType, SCREEN_HEIGHT, SCREEN_WIDTH, @@ -30,6 +31,8 @@ import {FriendsButton, BasicButton} from '../common'; import ToggleButton from './ToggleButton'; import {ChatContext} from '../../App'; import {useNavigation} from '@react-navigation/core'; +import {ChatListScreen} from '../../screens'; +import {ERROR_UNABLE_CONNECT_CHAT} from '../../constants/strings'; interface ProfileBodyProps { onLayout: (event: LayoutChangeEvent) => void; @@ -97,19 +100,12 @@ const ProfileBody: React.FC = ({ }; const onPressMessage = async () => { - let connected: boolean = await connectChatAccount( - loggedInUserId, - chatClient, - ); - if (connected) { - const channel = chatClient.channel('messaging', { - members: [loggedInUserId, String(userXId)], - }); - channel.create(); + if (chatClient.user && userXId) { + const channel = await createChannel(loggedInUserId, userXId, chatClient); setChannel(channel); navigation.navigate('Chat'); } else { - Alert.alert('Something wrong with chat'); + Alert.alert(ERROR_UNABLE_CONNECT_CHAT); } }; diff --git a/src/constants/strings.ts b/src/constants/strings.ts index 94f5552f..bdb94fba 100644 --- a/src/constants/strings.ts +++ b/src/constants/strings.ts @@ -9,6 +9,7 @@ export const ERROR_AUTHENTICATION = 'An error occurred during authentication. Pl export const ERROR_BADGES_EXCEED_LIMIT = 'You can\'t have more than 5 badges!'; export const ERROR_CATEGORY_CREATION = 'There was a problem creating your categories. Please refresh and try again.'; export const ERROR_CATEGORY_UPDATE = 'There was a problem updating your categories. Please refresh and try again'; +export const ERROR_CHAT_CONNECTION = `Unable to establish chat connection`; export const ERROR_DELETE_CATEGORY = 'There was a problem while deleting category. Please try again'; export const ERROR_DELETE_MOMENT = 'Unable to delete moment, please try again later!'; export const ERROR_DELETED_OBJECT = 'Oh sad! Looks like the comment / moment was deleted by the user'; @@ -35,7 +36,6 @@ export const ERROR_PROFILE_CREATION_SHORT = 'Profile creation failed πŸ˜“'; export const ERROR_PROFILE_UPDATE_SHORT = 'Profile update failed. πŸ˜”'; export const ERROR_PWD_ACCOUNT = (str: string) => `Please make sure that the email / username entered is registered with us. You may contact our customer support at ${str}`; export const ERROR_REGISTRATION = (str: string) => `Registration failed πŸ˜”, ${str}`; -export const ERROR_CHAT_CONNECTION = `Unable to establish chat connection`; export const ERROR_SELECT_BIRTHDAY = 'Please select your birthday'; export const ERROR_SELECT_CLASS_YEAR = 'Please select your Class Year'; export const ERROR_SELECT_GENDER = 'Please select your gender'; @@ -45,6 +45,7 @@ export const ERROR_SOMETHING_WENT_WRONG = 'Oh dear, don’t worry someone will b export const ERROR_SOMETHING_WENT_WRONG_REFRESH = "Ha, looks like this one's on us, please refresh and try again"; export const ERROR_SOMETHING_WENT_WRONG_RELOAD = "You broke it, Just kidding! we don't know what happened... Please reload the app and try again"; export const ERROR_TWILIO_SERVER_ERROR = 'mhm, looks like that is an invalid phone number or our servers are down, please try again in a few mins'; +export const ERROR_UNABLE_CONNECT_CHAT = 'Unable to connect chat'; export const ERROR_UNABLE_TO_FIND_PROFILE = 'We were unable to find this profile. Please check username and try again'; export const ERROR_UNABLE_TO_VIEW_PROFILE = 'Unable to view this profile'; export const ERROR_UPLOAD = 'An error occurred while uploading. Please try again!'; diff --git a/src/screens/chat/ChatScreen.tsx b/src/screens/chat/ChatScreen.tsx index 59c53c99..1554274d 100644 --- a/src/screens/chat/ChatScreen.tsx +++ b/src/screens/chat/ChatScreen.tsx @@ -12,6 +12,7 @@ import { import {ChatContext} from '../../App'; import ChatHeader from '../../components/messages/ChatHeader'; import {MainStackParams} from '../../routes'; +import {ScreenType} from '../../types'; import {isIPhoneX} from '../../utils'; type ChatScreenNavigationProp = StackNavigationProp; @@ -32,7 +33,7 @@ const ChatScreen: React.FC = () => { // unable to figure out the padding issue, a hacky solution {paddingBottom: isIPhoneX() ? tabbarHeight + 20 : tabbarHeight + 50}, ]}> - + {}} /> diff --git a/src/store/initialStates.ts b/src/store/initialStates.ts index 02331eb6..7fd3ac5a 100644 --- a/src/store/initialStates.ts +++ b/src/store/initialStates.ts @@ -117,6 +117,7 @@ export const EMPTY_SCREEN_TO_USERS_LIST: Record< [ScreenType.Search]: EMPTY_USERX_LIST, [ScreenType.Notifications]: EMPTY_USERX_LIST, [ScreenType.SuggestedPeople]: EMPTY_USERX_LIST, + [ScreenType.Chat]: EMPTY_USERX_LIST, }; export const INITIAL_CATEGORIES_STATE = { -- cgit v1.2.3-70-g09d2