-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvoContainer.js
70 lines (63 loc) · 2.11 KB
/
ConvoContainer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import React, { useEffect, useState, createContext } from 'react'
import { Query } from 'react-apollo'
import { ALL_CHATS_QUERY } from './Queries/AllChats'
import User, { CURRENT_USER_QUERY } from './Queries/User'
import { useQuery, useSubscription } from 'react-apollo-hooks'
export const ChatCtx = createContext([undefined, () => {}])
const ConvoContainer = ({ children }) => {
const [chatId, setChatId] = useState(undefined)
const { data } = useQuery(ALL_CHATS_QUERY)
const formatted = (userChats, currentUser) => {
if (userChats) {
return userChats
.filter(msg => msg.messages)
.map(chatObj => {
let newMsgs = chatObj.messages.filter(msg => msg.from.id !== currentUser.id && !msg.seen)
let len = chatObj.messages.length - 1
const { messages, users } = chatObj
let [usr] = users.filter(usr => usr.id !== currentUser.id)
let img = usr.img.length ? usr.img.find(img => img.default).img_url : profileStandIn
return {
id: chatObj.id,
from: usr.firstName,
fromId: usr.id,
text: messages[len].text,
img: img,
time: messages[len].createdAt,
newMsgs: newMsgs.length,
typing: chatObj.typing.map(user => user.firstName)
}
})
.sort((a, b) => {
let dateA = new Date(a.time)
let dateB = new Date(b.time)
return dateB - dateA
})
} else return undefined
}
const selectedChat = !data.getUserChats
? null
: data.getUserChats.find(chat => chat.id === chatId)
return (
<Query query={CURRENT_USER_QUERY}>
{({ data: { currentUser } }) => {
const formattedChats = formatted(data.getUserChats, currentUser)
return (
<ChatCtx.Provider
value={{
chatId,
setChat: setChatId,
chat: selectedChat,
currentUser,
formattedChats,
data
}}
>
{children}
</ChatCtx.Provider>
)
}}
</Query>
)
}
export default ConvoContainer