Skip to content

Instantly share code, notes, and snippets.

@jedwards1211
Created April 3, 2019 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jedwards1211/807175e805bdf7008b9cb5b0d3e19077 to your computer and use it in GitHub Desktop.
Save jedwards1211/807175e805bdf7008b9cb5b0d3e19077 to your computer and use it in GitHub Desktop.
/**
* @prettier
*/
/* eslint-env browser */
declare module.exports: Promise<any>
if (typeof document === 'undefined') module.exports = new Promise(() => {})
else {
var lc = document.createElement('script')
lc.type = 'text/javascript'
lc.async = true
lc.src =
('https:' == document.location.protocol ? 'https://' : 'http://') +
'cdn.livechatinc.com/tracking.js'
var s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore(lc, s)
module.exports = new Promise((resolve, reject) => {
lc.onload = () => {
const { LC_API } = window
LC_API.on_after_load = () => resolve(LC_API)
}
lc.onerror = reject
})
}
/**
* @flow
* @prettier
*/
import * as React from 'react'
import { Query } from 'react-apollo'
import gql from 'graphql-tag'
import type { QueryRenderProps } from 'react-apollo'
import livechatPromise from '../util/livechat'
const query = gql`
query OpenChat {
currentUser {
id
email
}
}
`
// @graphql-to-flow auto-generated
type QueryData = {
currentUser: ?{
id: number,
email: ?string,
},
}
type ChildProps = {
openRequested: boolean,
onClick: (e: SyntheticMouseEvent<any>) => any,
}
export type Props = {
children: ChildProps => React.Node,
}
const OpenChat = ({ children }: Props): React.Node => {
const [livechat, setLivechat] = React.useState(null)
const [openRequested, setOpenRequested] = React.useState(false)
React.useEffect(() => {
livechatPromise.then(setLivechat)
}, [])
return (
<Query query={query}>
{({ loading, data }: QueryRenderProps<QueryData>) => {
const { currentUser } = data || {}
const { email } = currentUser || {}
if (openRequested && livechat && !loading) {
livechat.set_visitor_email(email)
livechat.open_chat_window()
setOpenRequested(false)
}
return children({
onClick: (e: SyntheticMouseEvent<any>) => {
setOpenRequested(true)
},
openRequested,
})
}}
</Query>
)
}
export default OpenChat
@jedwards1211
Copy link
Author

jedwards1211 commented Apr 3, 2019

Note: email could be undefined and this code is intended to work in that case, but even if I change the condition to

if (openRequested && livechat && !loading && email) {

the email still doesn't show up the first time chat window opens; only the second time

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment