{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/connect-the-frontend-to-adminchannel","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Connect the Frontend to AdminChannel\",\n  \"order\": 32,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"react\", \"phoenix\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Connect the Frontend to AdminChannel\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Connect frontend\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Display active users\")), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"First we'll update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat\"), \" component to add the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AdminChannel\"), \" to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"configureChannels\"), \" function. That way, when a user opens the chat window, they are subscribed to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"active_users\"), \" topic, which adds them to the list of active users stored in ETS and keeps track of their status with Presence.\"), mdx(\"p\", null, \"Then we need to update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat-frontend\"), \" to list all users, make them selectable, retrieve messages, and give our admin the ability to respond.\"), mdx(\"h2\", null, \"Updating phoenix-chat\"), mdx(\"p\", null, \"Our update to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat\"), \" component is pretty simple. Within the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"configureChannels\"), \" function, all we have to do is add a new channel called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"adminChannel\"), \" and join it. Then on \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"componentWillUnmount\"), \", we'll leave the channel.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\nexport class PhoenixChat extends React.Component {\\n\\n  componentWillUnmount() {\\n    this.channel.leave()\\n    this.adminChannel.leave()\\n  }\\n\\n  configureChannels() {\\n    this.channel = this.socket.channel(`room:${room}`)\\n    ...\\n\\n    this.adminChannel = this.socket.channel(`admin:active_users`)\\n    this.adminChannel.join()\\n      .receive(\\\"ok\\\", () => {\\n        console.log(`Succesfully joined the active_users topic.`)\\n      })\\n  }\\n\\n  ...\\n\\n\")), mdx(\"p\", null, \"And since we got rid of the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"from\"), \" field, we need to update the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"from\"), \" constant to determine on which side our messages should appear.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nexport class PhoenixChatSidebar extends React.Component {\\n  ...\\n\\n  render() {\\n    const list = !this.props.messages\\n      ? null\\n      : this.props.messages.map(({ body, id, anonymous_user_id }, i) => {\\n      const right = anonymous_user_id === localStorage.phoenix_chat_uuid\\n\\n      ...\\n    })\\n  }\\n\\n}\\n...\\n\")), mdx(\"p\", null, \"And that's all we have to change on our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat\"), \" component to connect to the admin channel.\"), mdx(\"h2\", null, \"Adding AdminChannel to Chat\"), mdx(\"p\", null, \"Now we need to add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Presence\"), \" to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat\"), \" component, which can then pass it down to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"Whent the component mounts, we want to initialize the socket and set up the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"adminChannel\"), \", which we do within the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"configureAdminChannel\"), \" function.\"), mdx(\"p\", null, \"Within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"configureAdminChannel\"), \", we set the topic to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"active_users\"), \" and listen for a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"presence_state\"), \" or \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"presence_diff\"), \" action, which lets us know a user joins or leaves the socket. Whenever a change occurs, we update the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.state.presences\"), \" object, which triggers a re-render.\"), mdx(\"p\", null, \"Then we pass \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.state.presences\"), \" as props to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Sidebar\"), \" component. Finally we connect our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat\"), \" component to Redux and map the state of the user to the Redux \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \". It's a lot of code, but you've seen most of it before.\"), mdx(\"p\", null, mdx(\"strong\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ npm install --save phoenix\\n\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import React from \\\"react\\\"\\nimport cssModules from \\\"react-css-modules\\\"\\nimport { Socket, Presence } from \\\"phoenix\\\"\\nimport { connect } from \\\"react-redux\\\"\\nimport style from \\\"./style.css\\\"\\n\\nimport { default as Sidebar } from \\\"../Sidebar\\\"\\n\\nexport class Chat extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.state = {\\n      presences: {}\\n    }\\n  }\\n\\n  componentDidMount() {\\n    const params = this.props.user\\n    this.socket = new Socket(\\\"ws://localhost:4000/socket\\\", { params })\\n    this.socket.connect()\\n    this.configureAdminChannel()\\n  }\\n\\n  ...\\n\\n}\\n\\nconst mapStateToProps = state => ({\\n  user: state.user\\n})\\n\\nexport default connect(mapStateToProps)(cssModules(Chat, style))\\n\\n\")), mdx(\"p\", null, \"Now configure the admin channel.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nexport class Chat extends React.Component {\\n  ...\\n\\n  configureAdminChannel() {\\n    this.adminChannel = this.socket.channel(\\\"admin:active_users\\\")\\n    this.adminChannel.on(\\\"presence_state\\\", state => {\\n      const presences = Presence.syncState(this.state.presences, state)\\n      console.log('Presences after sync: ', presences)\\n      this.setState({ presences })\\n    })\\n    this.adminChannel.on(\\\"presence_diff\\\", state => {\\n      const presences = Presence.syncDiff(this.state.presences, state)\\n      console.log('Presences after diff: ', presences)\\n      this.setState({ presences })\\n    })\\n    this.adminChannel.join()\\n      .receive(\\\"ok\\\", ({ id }) => {\\n        console.log(`${id} succesfully joined the active_users topic.`)\\n      })\\n  }\\n\\n  ...\\n}\\n...\\n\")), mdx(\"p\", null, \"And finally render the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Chat\"), \" component.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nexport class Chat extends React.Component {\\n...\\n\\n  render() {\\n    return (\\n      <div>\\n        <Sidebar\\n          presences={this.state.presences} />\\n        <div className={style.chatWrapper}>\\n          chat me\\n        </div>\\n        { this.props.children }\\n      </div>\\n    )\\n  }\\n}\\n...\\n\")), mdx(\"p\", null, \"The next thing we need to do is list our presences and users in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Sidebar\"), \". We're going to create two functions within this component: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"listBy\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Sidebar\"), \" renders, it creates a completely new constant called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"import React from \\\"react\\\"\\nimport cssModules from \\\"react-css-modules\\\"\\nimport { Presence } from \\\"phoenix\\\"\\nimport style from \\\"./style.css\\\"\\n\\nconst listBy = (id, { metas: [first, ...rest] }) => {\\n  first.count = rest.length + 1\\n  first.id = id\\n  return first\\n}\\n\\nconst renderList = props => {\\n  return Presence.list(props.presences, listBy).map(({ id }) => {\\n    return <div key={id}>{id}</div>\\n  })\\n}\\n\\nexport const Sidebar = props => {\\n  return <div className={style.sidebar}>{renderList(props)}</div>\\n}\\n\\nexport default cssModules(Sidebar, style)\\n\")), mdx(\"p\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"renderList\"), \" function is the return value from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Phoenix.list\"), \". Note that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Phoenix.list\"), \" here is different on the frontend than the backend. As in, it's \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/1.2.0-rc.1/Phoenix.Presence.html#list/2\",\n    \"parentName\": \"p\"\n  }, \"not this\"), \" list, it's \", mdx(\"a\", {\n    \"href\": \"https://github.com/phoenixframework/phoenix/blob/master/priv/static/phoenix.js#L130-L182\",\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"From the docs:\"), mdx(\"blockquote\", null, mdx(\"p\", {\n    \"parentName\": \"blockquote\"\n  }, \"By default, all presence metadata is returned, but a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"listBy\"), \" function can be supplied to allow the client to select which metadata to use for a given presence.\")), mdx(\"p\", null, \"So within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"listBy\"), \" function, we take in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"props.presence\"), \". Each \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"presence\"), \" object has the keys \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"metas\"), \". \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"metas\"), \" contains a list of all the devices with which the user has been present. We are going to use our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" from each device, but we will do it in case we need to track the presence of our admin.\"), mdx(\"p\", null, \"We use object \", mdx(\"a\", {\n    \"href\": \"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\",\n    \"parentName\": \"p\"\n  }, \"destructuring assignment\"), \" and a \", mdx(\"a\", {\n    \"href\": \"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator\",\n    \"parentName\": \"p\"\n  }, \"spread operator\"), \" to pull out the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"first\"), \" value from our list of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"metas\"), \". From there we are going to add the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"count\"), \" field, which lets us know how many devices are connected and the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" of the user's presence.\"), mdx(\"p\", null, \"Now, back to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"renderList\"), \". After passing through \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Phoenix.list\"), \" and going through the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"listBy\"), \" function, we have a list of presences that have been filtered down to one instance. We then \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"map\"), \" over the list and return jsx objects for each presence.\"), mdx(\"p\", null, \"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.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Connect the Frontend to AdminChannel Connect frontend Display active users Now that our backend is keeping track of active users, we need to…","frontmatter":{"title":"Connect the Frontend to AdminChannel","order":32,"active":true,"free":false,"tech":["react","phoenix"]}}},"pageContext":{"slug":"connect-the-frontend-to-adminchannel","prevNode":{"frontmatter":{"title":"Broadcast Active and Inactive Users","active":true,"free":false,"order":31,"tech":["phoenix"]},"fields":{"slug":"broadcast-active-and-inactive-users"}},"nextNode":{"frontmatter":{"title":"Join Room and Receive Messages","active":true,"free":false,"order":33,"tech":["react"]},"fields":{"slug":"join-room-and-receive-messages"}}}},"staticQueryHashes":["1723017916"]}