Now that our backend is keeping track of active users, we need to connect our frontend to list them. From there, our admin can select a conversation and respond to incoming chats from anonymous users.
First we'll update our phoenix-chat component to add the AdminChannel to the configureChannels function. That way, when a user opens the chat window, they are subscribed to the active_users topic, which adds them to the list of active users stored in ETS and keeps track of their status with Presence.
Then we need to update our phoenix-chat-frontend to list all users, make them selectable, retrieve messages, and give our admin the ability to respond.
Our update to the phoenix-chat component is pretty simple. Within the configureChannels function, all we have to do is add a new channel called adminChannel and join it. Then on componentWillUnmount, we'll leave the channel.
...export class PhoenixChat extends React.Component { componentWillUnmount() { this.channel.leave() this.adminChannel.leave() } configureChannels() { this.channel = this.socket.channel(`room:${room}`) ... this.adminChannel = this.socket.channel(`admin:active_users`) this.adminChannel.join() .receive("ok", () => { console.log(`Succesfully joined the active_users topic.`) }) } ...And since we got rid of the from field, we need to update the from constant to determine on which side our messages should appear.
...export class PhoenixChatSidebar extends React.Component { ... render() { const list = !this.props.messages ? null : this.props.messages.map(({ body, id, anonymous_user_id }, i) => { const right = anonymous_user_id === localStorage.phoenix_chat_uuid ... }) }}...And that's all we have to change on our phoenix-chat component to connect to the admin channel.
Now we need to add Presence to our Chat component, which can then pass it down to the Sidebar component, which renders the list of active users. We are going to handle all of this in local state for the time being, but we may eventually move this into Redux if it makes sense.
Whent the component mounts, we want to initialize the socket and set up the adminChannel, which we do within the configureAdminChannel function.
Within configureAdminChannel, we set the topic to active_users and listen for a presence_state or presence_diff action, which lets us know a user joins or leaves the socket. Whenever a change occurs, we update the this.state.presences object, which triggers a re-render.
Then we pass this.state.presences as props to our Sidebar component. Finally we connect our Chat component to Redux and map the state of the user to the Redux state. It's a lot of code, but you've seen most of it before.
Note: we're eventually going to move all of this logic to Redux. Generally speaking, when you find yourself working with components that contain their own logic, you probably want to consider moving that logic to Redux.
$ npm install --save phoeniximport React from "react"import cssModules from "react-css-modules"import { Socket, Presence } from "phoenix"import { connect } from "react-redux"import style from "./style.css"import { default as Sidebar } from "../Sidebar"export class Chat extends React.Component { constructor(props) { super(props) this.state = { presences: {} } } componentDidMount() { const params = this.props.user this.socket = new Socket("ws://localhost:4000/socket", { params }) this.socket.connect() this.configureAdminChannel() } ...}const mapStateToProps = state => ({ user: state.user})export default connect(mapStateToProps)(cssModules(Chat, style))Now configure the admin channel.
...export class Chat extends React.Component { ... configureAdminChannel() { this.adminChannel = this.socket.channel("admin:active_users") this.adminChannel.on("presence_state", state => { const presences = Presence.syncState(this.state.presences, state) console.log('Presences after sync: ', presences) this.setState({ presences }) }) this.adminChannel.on("presence_diff", state => { const presences = Presence.syncDiff(this.state.presences, state) console.log('Presences after diff: ', presences) this.setState({ presences }) }) this.adminChannel.join() .receive("ok", ({ id }) => { console.log(`${id} succesfully joined the active_users topic.`) }) } ...}...And finally render the Chat component.
...export class Chat extends React.Component {... render() { return ( <div> <Sidebar presences={this.state.presences} /> <div className={style.chatWrapper}> chat me </div> { this.props.children } </div> ) }}...The next thing we need to do is list our presences and users in our Sidebar. We're going to create two functions within this component: listBy and renderList. The first function orders our data and the second returns the jsx that we will render. We're going to use a lot from the new ES205 syntax, so a more detailed explanation of each is provided below the codeblock.
Keep in mind that functions should sometimes live outside of the component. This is because React will always redraw anything that is in a nested function because each time Sidebar renders, it creates a completely new constant called listBy. This optimization doesn't usually make a difference, but it's worth keeping in mind when you have components that are rendered a lot.
import React from "react"import cssModules from "react-css-modules"import { Presence } from "phoenix"import style from "./style.css"const listBy = (id, { metas: [first, ...rest] }) => { first.count = rest.length + 1 first.id = id return first}const renderList = props => { return Presence.list(props.presences, listBy).map(({ id }) => { return <div key={id}>{id}</div> })}export const Sidebar = props => { return <div className={style.sidebar}>{renderList(props)}</div>}export default cssModules(Sidebar, style)The renderList function is the return value from Phoenix.list. Note that Phoenix.list here is different on the frontend than the backend. As in, it's not this list, it's this one. There currently isn't much in the way of docs, but that's the price you pay for working with cutting-edge frameworks.
From the docs:
By default, all presence metadata is returned, but a
listByfunction can be supplied to allow the client to select which metadata to use for a given presence.
So within our listBy function, we take in props.presence. Each presence object has the keys id and metas. metas contains a list of all the devices with which the user has been present. We are going to use our listBy function to prioritize the first device/tab registered for each user. This is not especially important for us since each anonymous user will generate a new uuid from each device, but we will do it in case we need to track the presence of our admin.
We use object destructuring assignment and a spread operator to pull out the first value from our list of metas. From there we are going to add the count field, which lets us know how many devices are connected and the id of the user's presence.
Now, back to our renderList. After passing through Phoenix.list and going through the listBy function, we have a list of presences that have been filtered down to one instance. We then map over the list and return jsx objects for each presence.
Next we're going to make these users click-able so an admin can connect to a channel to receive and respond to message from anonymous users.
Previous: Broadcast Active and Inactive UsersNext: Join Room and Receive Messages