Adrien BĂ©raud | 35e7d7c | 2021-04-13 03:28:39 -0400 | [diff] [blame] | 1 | import CircularProgress from '@material-ui/core/CircularProgress'; |
| 2 | import React from 'react'; |
| 3 | import MessageList from './MessageList'; |
| 4 | import SendMessageForm from './SendMessageForm'; |
| 5 | import authManager from '../AuthManager' |
| 6 | import Conversation from '../../../model/Conversation'; |
| 7 | |
| 8 | class ConversationView extends React.Component { |
| 9 | constructor(props) { |
| 10 | super(props) |
| 11 | this.state = { |
| 12 | loaded:false, |
| 13 | error: false, |
| 14 | messages:[] |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | componentDidMount() { |
| 19 | this.controller = new AbortController() |
| 20 | if (!this.state.loaded) { |
| 21 | authManager.fetch(`/api/accounts/${this.props.accountId}/conversations/${this.props.conversationId}`, {signal: this.controller.signal}) |
| 22 | .then(res => res.json()) |
| 23 | .then(result => { |
| 24 | console.log(result) |
| 25 | this.setState({ |
| 26 | loaded: true, |
| 27 | conversation: Conversation.from(this.props.accountId, result)// result.map(account => Account.from(account)), |
| 28 | }) |
| 29 | }, error => { |
| 30 | console.log(`get error ${error}`) |
| 31 | this.setState({ |
| 32 | loaded: true, |
| 33 | error: true |
| 34 | }) |
| 35 | }) |
| 36 | } |
| 37 | } |
| 38 | componentDidUpdate(prevProps, prevState) { |
| 39 | console.log("componentDidUpdate " + this.props.conversationId) |
| 40 | if (this.props.conversationId !== prevProps.conversationId) { |
| 41 | if (this.state.loaded === true) { |
| 42 | this.setState({ |
| 43 | loaded:false, |
| 44 | error: false, |
| 45 | messages:[] |
| 46 | }) |
| 47 | } |
| 48 | this.controller = new AbortController() |
| 49 | authManager.fetch(`/api/accounts/${this.props.accountId}/conversations/${this.props.conversationId}`, {signal: this.controller.signal}) |
| 50 | .then(res => res.json()) |
| 51 | .then(result => { |
| 52 | console.log(result) |
| 53 | this.setState({ |
| 54 | loaded: true, |
| 55 | conversation: Conversation.from(this.props.accountId, result)// result.map(account => Account.from(account)), |
| 56 | }) |
| 57 | }, error => { |
| 58 | console.log(`get error ${error}`) |
| 59 | this.setState({ |
| 60 | loaded: true, |
| 61 | error: true |
| 62 | }) |
| 63 | }) |
| 64 | } |
| 65 | } |
| 66 | componentWillUnmount() { |
| 67 | this.controller.abort() |
| 68 | } |
| 69 | |
| 70 | render() { |
| 71 | if (this.state.loaded === false) { |
| 72 | return <CircularProgress /> |
| 73 | } else if (this.state.error === true) { |
| 74 | return <div>Error loding {this.props.conversationId}</div> |
| 75 | } else { |
| 76 | return <React.Fragment> |
| 77 | <MessageList conversation={this.state.conversation} messages={this.state.messages} /> |
| 78 | <SendMessageForm sendMessage={this.sendMessage} /> |
| 79 | </React.Fragment> |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | export default ConversationView |