Skip to content

Instantly share code, notes, and snippets.

@andreimc
Created February 27, 2019 02:41
Show Gist options
  • Save andreimc/4a761bcf4f52436e68bab34e854893bb to your computer and use it in GitHub Desktop.
Save andreimc/4a761bcf4f52436e68bab34e854893bb to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
import Helmet from 'react-helmet'
import { SessionUser } from '../../services/auth'
import { theme } from '../../styles/GlobalStyles'
interface State {
chatra: any
currentUser: SessionUser | null
restartChat: boolean
}
interface Props {
currentUser: SessionUser | null
logout: boolean
login: boolean
}
export default class ChatClient extends Component<Props, State> {
public static getDerivedStateFromProps(props: Props, state: State) {
if (props.currentUser !== state.currentUser) {
return { currentUser: props.currentUser, restartChat: true }
} else {
return { ...state, restartChat: false }
}
}
public state: State = {
chatra: null,
currentUser: null,
restartChat: false
}
// tslint:disable-next-line:variable-name
private _interval: any | undefined
public componentDidMount() {
if (typeof window === 'undefined') {
return
}
this.setState({
currentUser: this.props.currentUser
})
const windowlocal = window as any
if (windowlocal.Chatra) {
this.setState({
chatra: windowlocal.Chatra
})
} else {
this.listenForJs()
}
}
public listenForJs() {
if (this._interval) {
return true
}
const windowlocal = window as any
this._interval = setInterval(() => {
if (windowlocal.Chatra) {
this.setState({ chatra: windowlocal.Chatra })
clearInterval(this._interval!)
}
}, 100)
return false
}
public renderJs() {
const { currentUser } = this.state
const locWin = window as any
const clientId = currentUser ? currentUser.clienId : null
locWin.ChatraID = 'chatra_id'
locWin.ChatraSetup = {
clientId,
colors: {
buttonBg: theme.primaryColor
}
}
if (currentUser) {
locWin.ChatraIntegration = {
name: currentUser.name,
email: currentUser.email
}
}
return (
<Helmet>
<script src="https://call.chatra.io/chatra.js" async />
</Helmet>
)
}
public setUser(currentUser: SessionUser | null) {
const locWin = window as any
if (currentUser) {
locWin.ChatraIntegration = {
name: currentUser.name,
email: currentUser.email
}
} else {
locWin.ChatraIntegration = null
}
}
public restartChat() {
const { currentUser } = this.state
const clientId = currentUser ? currentUser.clientId : null
const locWin = window as any
this.setUser(currentUser)
locWin.Chatra._clientId = clientId
locWin.Chatra.restart()
}
public render() {
if (typeof window === 'undefined') {
return null
}
if (!this.state.chatra) {
return this.renderJs()
} else {
if (this.state.restartChat || this.props.login || this.props.logout) {
this.restartChat()
}
return null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment