File size: 1,880 Bytes
f5071ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
75
76
77
import gql from 'graphql-tag';
import React from 'react';
import { useCallback } from 'react';
import styled from 'styled-components';
import * as fragments from '../../graphql/fragments';
import UsersList from '../UsersList';
import ChatCreationNavbar from './ChatCreationNavbar';
import { History } from 'history';
import { useAddChatMutation } from '../../graphql/types';
import { writeChat } from '../../services/cache.service';

// eslint-disable-next-line
const Container = styled.div`
  height: calc(100% - 56px);
  overflow-y: overlay;
`;

// eslint-disable-next-line
const StyledUsersList = styled(UsersList)`
  height: calc(100% - 56px);
`;

gql`
  mutation AddChat($recipientId: ID!) {
    addChat(recipientId: $recipientId) {
      ...Chat
    }
  }
  ${fragments.chat}
`;

interface ChildComponentProps {
  history: History;
}

const ChatCreationScreen: React.FC<ChildComponentProps> = ({ history }) => {
  const [addChat] = useAddChatMutation();

  const onUserPick = useCallback(
    (user) =>
      addChat({
        optimisticResponse: {
          __typename: 'Mutation',
          addChat: {
            __typename: 'Chat',
            id: Math.random().toString(36).substr(2, 9),
            name: user.name,
            picture: user.picture,
            lastMessage: null,
          },
        },
        variables: {
          recipientId: user.id,
        },
        update: (client, { data }) => {
          if (data && data.addChat) {
            writeChat(client, data.addChat);
          }
        },
      }).then((result) => {
        if (result && result.data !== null) {
          history.push(`/chats/${result.data!.addChat!.id}`);
        }
      }),
    [addChat, history]
  );

  return (
    <div>
      <ChatCreationNavbar history={history} />
      <UsersList onUserPick={onUserPick} />
    </div>
  );
};

export default ChatCreationScreen;