<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Coding Artist - Medium]]></title>
        <description><![CDATA[Providing journeys for developers who see the web as their canvas - Medium]]></description>
        <link>https://medium.com/coding-artist?source=rss----6df8bca0c0de---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Coding Artist - Medium</title>
            <link>https://medium.com/coding-artist?source=rss----6df8bca0c0de---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 26 Nov 2026 05:29:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/coding-artist" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Full-Stack React With Phoenix (Chapter 10 | Moving Forward)]]></title>
            <link>https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-10-moving-forward-69303b6b75b0?source=rss----6df8bca0c0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/69303b6b75b0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Michael Mangialardi]]></dc:creator>
            <pubDate>Fri, 04 Aug 2017 01:01:19 GMT</pubDate>
            <atom:updated>2017-08-05T18:52:42.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*166lO_OciKzweQBoOmQq3g.png" /></figure><h3>Table of Contents</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Chapter 1 | Why Bother?</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Chapter 2 | Learning the Basics of Elixir</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4">Chapter 3 | Introduction to Phoenix</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-4-implementing-react-716979133669">Chapter 4 | Implementing React</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-5-working-with-postgresql-83ec4f3286b2">Chapter 5 | Working With PostgreSQL</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-6-creating-a-postgresql-api-service-9f2775161d3f">Chapter 6 | Creating a PostgreSQL API Service</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-7-crud-operations-79d4e5af9a0d">Chapter 7 | CRUD Operations</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-8-user-authentication-fb1ff48a5e51">Chapter 8 | User Authentication</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-9-channels-245a24647e84">Chapter 9 | Channels</a></p><p>In just 9 chapters, we’ve learned the fundamentals of full-stack web development using Phoenix on the backend and React on the frontend. You should have enough knowledge to create your own full-stack apps and dive deeper into Phoenix and Elixir. Hopefully, you’ve enjoyed this book so much that you have a similar feeling to the “show hole”.</p><p>Just like finishing a show on Netflix, you may be wondering what to do next. To wrap up this book, I’ll provide a few suggestions for what I recommend to learn next.</p><h3>Recommend Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*5wp47e89V2kIvfv4k8Lb_Q.png" /></figure><h4>Phoenix Version 1.3</h4><p>Out of anything you could learn, I would do this next. Phoenix has released an updated version since the release of this book.</p><p>Fortunately, it’s backward compatible and there’s plenty of information on what has changed and how to adjust existing projects via the <a href="https://gist.github.com/chrismccord/71ab10d433c98b714b75c886eff17357">official documentation</a>.</p><p>There is also a write-up that can be found <a href="https://medium.com/wemake-services/why-changes-in-phoenix-1-3-are-so-important-2d50c9bdabb9">here</a> covering the important changes with the new release and how to reimplement things accordingly.</p><h4>Redux</h4><p>Redux is a buzz word that is often thrown around when looking at React tutorials.</p><p>It’s one of those things that you start using and you wonder: “Why did I ever not do this before?” The issue is that this has caused a lot of tutorials to implement Redux in tutorials without much explanation. For that reason, I purposely kept Redux out of this book. Although, it would have made some things that we were doing much smoother.</p><p>Essentially, Redux provides an alternative to having a bunch of different local states managing data. Local states can get quite confusing to keep track of all the data in your entire React application much like managing your own money without a bank would be confusing.</p><p>Redux solves this issue by storing all of your data in one central location and allowing all your components access to read and request changes.</p><p>I wrote an ebook called <a href="https://leanpub.com/reduxfromscratch">Redux From Scratch</a> which takes you through the basics of implementing Redux in full-stack React development.</p><h4>React VR</h4><p>If you’re looking for a more creative, experimental skill to learn next. Consider learning the basics of React VR and adding your own Phoenix backed.</p><p>I wrote a book called <a href="https://leanpub.com/learnreactvr">Learn React VR</a> which takes you through all the fundamentals.</p><h4>Elixir</h4><p>In this book, we wrote Phoenix code was built off of the Elixir language. Although we covered the basics of Elixir, there’s still a ton more that you could do.</p><p>I recommend trying to <a href="https://www.google.com/search?q=python+scripts&amp;oq=python+scripts&amp;aqs=chrome..69i57j69i59j0l4.3966j0j4&amp;sourceid=chrome&amp;ie=UTF-8">reimplement Python scripts in Elixir</a> and checking out the book <a href="http://amzn.to/2vnEmh3"><em>Programming Elixir 1.3</em></a><em>.</em></p><h4><strong>GraphQL</strong></h4><p>Instead of doing RESTful APIs like, we did in this book, GraphQL makes some significant improvements.</p><p>GraphQL provides a way to describe data in your API using queries.</p><p>I won’t bother explaining what it is because <a href="https://medium.freecodecamp.org/so-whats-this-graphql-thing-i-keep-hearing-about-baf4d36c20cf">this article</a> does a fabulous job.</p><p>Once you read through that, the <a href="http://graphql.org/learn/">official documentation</a> is a solid place to start learning.</p><h4><strong>Preact</strong></h4><p>Preact is a fast 3kB alternative to React with the same ES6 API. In other words, it’s React but leaner and faster with only a <a href="https://preactjs.com/">few changes to get started</a>.</p><h4>Create Your Own Product</h4><p>While this is not a technology to learn, you can try to create your own React/Phoenix app as a learning experience. In my opinion, why not turn your side project into some sort of product? In other words, try out your own React/Phoenix project and see if you can monetize it in the process.</p><h3>Help Support the Author</h3><p>I don’t have much to say other than a big “thank you”. It’s people who take the time to read and provide feedback on my content that keeps me fueled.</p><p>I’ve put hours and hours and hours and hours into providing content for absolutely free. If you would like to help support me for all the hard work that has gone into providing people free content, please <a href="https://leanpub.com/u/mikemangialardi">pick up on of my ebooks</a> and <a href="https://www.patreon.com/codingartist">consider backing me on Patreon</a>.</p><p>Thanks again,<br>Mike Mangialardi<br>Founder of Coding Artist</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69303b6b75b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-10-moving-forward-69303b6b75b0">Full-Stack React With Phoenix (Chapter 10 | Moving Forward)</a> was originally published in <a href="https://medium.com/coding-artist">Coding Artist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack React With Phoenix (Chapter 9 | Channels)]]></title>
            <link>https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-9-channels-245a24647e84?source=rss----6df8bca0c0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/245a24647e84</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Michael Mangialardi]]></dc:creator>
            <pubDate>Fri, 04 Aug 2017 00:00:30 GMT</pubDate>
            <atom:updated>2017-08-11T16:51:53.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFGWD-5p8ilF_Z8VSqaGZw.png" /></figure><h3>Table of Contents</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Chapter 1 | Why Bother?</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Chapter 2 | Learning the Basics of Elixir</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4">Chapter 3 | Introduction to Phoenix</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-4-implementing-react-716979133669">Chapter 4 | Implementing React</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-5-working-with-postgresql-83ec4f3286b2">Chapter 5 | Working With PostgreSQL</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-6-creating-a-postgresql-api-service-9f2775161d3f">Chapter 6 | Creating a PostgreSQL API Service</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-7-crud-operations-79d4e5af9a0d">Chapter 7 | CRUD Operations</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-8-user-authentication-fb1ff48a5e51">Chapter 8 | User Authentication</a></p><h3>What Are Channels?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obaATrLVm8FLQmDgcR70WA.png" /></figure><h4>High-Level Understanding</h4><p>Channels provide bi-directional communication via messages.</p><p>Think of it like having walkie talkies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*cl0RFxTVcqj219LXOxht_Q.png" /></figure><p>By being on the same channel, two people could communicate messages with one another from both directions. In the same way, Phoenix channels enable communication to occur between the backend and the frontend (server and client).</p><p>This enables “real-time” features for applications built with React and Phoenix.</p><p>Some use cases of real-time features include instant messaging, document collaboration (multiple people editing a document at same time), analytics, and binary streaming.</p><p>In this chapter, we will be making a real-time chat application.</p><p>As mentioned, channels are based upon the sending and receiving of messages between the server and client. Because of this, channels include <em>senders </em>and <em>receivers</em>.</p><p>Just like in normal conversations, there is always a <em>topic </em>of conversation. Likewise, senders<em> broadcast</em> messages about certain topics. Receivers <em>subscribe </em>to topics to receive the messages that were broadcasted by the senders. Messages passing through a channel can have multiple receivers.</p><h4>Diving Deeper</h4><p>So far, we’ve described channels at a high-level. Let’s unpack the many layers in more specifics.</p><p><strong>Sockets<br></strong>A physical socket is a cylinder with two open ends:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*rlw2xm5YoAxVMup1BT-VzA.png" /></figure><p>In the same way, sockets in a technical sense are the tunnels for messages being passed on two open ends (the server and client).</p><p><strong>Socket Handlers<br></strong>As the <a href="https://hexdocs.pm/phoenix/channels.html#the-moving-parts">official documentation</a> summarizes nicely, Socket handlers are modules that authenticate and identify a socket connection and allow you to set default socket assigns for use in all channels.</p><p><strong>Topics<br></strong>Topics are string identifiers of what messages are about. By knowing what messages are about, we can make sure the messages end up in the right place when being handled.</p><p>The string identifiers are written about with the following syntax: topic:subtopic</p><p>An example would be foods:chicken.</p><p><strong>Messages<br></strong>Messages are structs that contain a <em>topic</em>, <em>event</em>, <em>payload</em>, and <em>ref</em>.</p><p><em>Topics </em>were just discussed.</p><p><em>Events</em> are the string for the event name.</p><p><em>Payloads </em>contain the data to be communicated within a message.</p><p><em>Refs </em>are unique string identifiers for a message.</p><p><strong>Channel Routes<br></strong>We mentioned <em>senders </em>and <em>receivers </em>which broadcast messages and subscribe to messages on certain topics accordingly. Channel routes are used to route topics with channel modules.</p><p>For example, let’s say we wanted to have a channel about <em>foods</em>. We could have something like this:</p><pre>channel &quot;foods:*&quot;, PhoenixApp.FoodsChannel</pre><p>The code above would route all discussion about <em>foods </em>into a channel module in a Phoenix app called <em>FoodsChannel</em>.</p><p>The * is a wildcard matcher for subtopics so requests for foods:chicken and foods:apples would both go into the <em>FoodsChannel</em>.</p><p><strong>Channel Modules<br></strong>Channel Modules (also just called channels) are basically bi-directional controllers. They contain events for <em>incoming </em>and <em>outgoing </em>stuff.</p><p><strong>Transports<br></strong>As the name suggests, the transport layer handles the transportation of messages into and out of a channel.</p><p><strong>PubSub<br></strong>The PubSub (publisher/subscriber) layer consists of using a predefined Phoenix.PubSub module. This module contains functions that handle certain tasks for organizing channel communication such as: <em>subscribing to topics</em>, <em>unsubscribing from topics</em>, and <em>broadcasting messages on a topic</em>.</p><h3>Creating a Phoenix/React Chat Room</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZpYDvTsAP9FMIwv9BqbBA.png" /></figure><h4>Configuring Our First Channel Topic</h4><p>Let’s generate a new Phoenix project called <em>chat_app</em>:</p><pre>mix phoenix.new chat_app<br>cd chat_app</pre><p>Open the project in a code editor of choice.</p><p>In lib/chat_app/endpoint.ex, there is an endpoint for communication via a socket already defined:</p><pre>defmodule ChatApp.Endpoint do<br>  use Phoenix.Endpoint, otp_app: :chat_app</pre><pre>  socket &quot;/socket&quot;, ChatApp.UserSocket</pre><pre># ....</pre><p>In web/channels/user_socket.ex, we have a socket for communication of messages with a transportation layer configured:</p><pre>transport :websocket, Phoenix.Transports.WebSocket</pre><p>In this file, we can uncomment the following line:</p><pre>## Channels<br>channel &quot;room:*&quot;, ChatApp.RoomChannel # uncommented</pre><p>The code above is saying: “Handle all subtopics of the <em>room </em>topic in our channel module called<em> RoomChannel.”</em></p><p><em>room </em>refers to having a single chat room that can have all sorts of subtopics.</p><p>Next, we need to write the code for our the channel module called <em>RoomChannel</em> which handles all the messages with a topic of <em>room</em>.</p><p>Create another file called <em>room_channel.ex </em>under web/channels.</p><p>In this file, we can add the following:</p><pre>defmodule ChatApp.RoomChannel do<br>  use Phoenix.Channel</pre><pre>  def join(&quot;room:lobby&quot;, _message, socket) do<br>    {:ok, socket}<br>  end<br><br>end</pre><p>In the code above, we are allowing anyone to join room:lobby topic and communication through the socket.</p><h4>Client Configuration</h4><p>Now, the client is ready to join the room:lobby topic in our channel to send messages. Let’s setup our React frontend to do this.</p><p>You should know the basic setup a React frontend but let’s do it together.</p><p>First, we install all dependencies:</p><pre>npm install --save react react-dom babel-preset-react</pre><p>Then, open <em>brunch-config.js </em>to apply the Babel preprocessing for our React code:</p><pre>plugins: {<br>  babel: {<br>    presets: [&quot;es2015&quot;, &quot;react&quot;],<br>    // Do not use ES6 compiler in vendor code<br>    ignore: [/web\/static\/vendor/]<br>  }<br>},</pre><p>In addition, we need to add a whitelist in under the <em>npm </em>options in this file so that it is clear that we are going to use <em>react</em> and <em>react-dom</em>:</p><pre>npm: {<br>  enabled: true,<br>  whitelist: [&quot;phoenix&quot;, &quot;phoenix_html&quot;, &quot;react&quot;, &quot;react-dom&quot;]<br>}</pre><p>We can create the target for our app in the <em>index.html.eex </em>template (delete everything else):</p><pre>&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;</pre><p>The <em>index.html.eex </em>template is nested within <em>app.html.eex</em>. The app template contains a pre-populated header which we can remove:</p><pre>&lt;header class=&quot;header&quot;&gt;<br>  &lt;nav role=&quot;navigation&quot;&gt;<br>    &lt;ul class=&quot;nav nav-pills pull-right&quot;&gt;<br>      &lt;li&gt;&lt;a href=&quot;<a href="http://www.phoenixframework.org/docs">http://www.phoenixframework.org/docs</a>&quot;&gt;Get Started&lt;/a&gt;&lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/nav&gt;<br>  &lt;span class=&quot;logo&quot;&gt;&lt;/span&gt;<br>&lt;/header&gt;</pre><pre>^^^ delete this</pre><p>Under web/static/js, let’s add <em>containers </em>and <em>presentationals </em>folders.</p><p>In web/static/js/app.js, we can write the top-level React component for our app which will render a container component called <em>Chat</em>:</p><pre>import &quot;phoenix_html&quot;;<br>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br>import Chat from &quot;./containers/Chat&quot;;</pre><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;Chat /&gt;<br>    )<br>  }<br>}</pre><pre>ReactDOM.render(<br>  &lt;App/&gt;,<br>  document.getElementById(&quot;app&quot;)<br>)</pre><p>Let’s create that <em>Chat </em>component in a file called <em>Chat.js </em>under the <em>containers </em>folder.</p><p>We can populate the shell of the code for this component:</p><pre>import React from &quot;react&quot;;</pre><pre>class Chat extends React.Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default Chat;</pre><p>After that, we want to connect to our socket and attempt to join the channel for our lobby:</p><pre>import React from &quot;react&quot;;<br>import {Socket} from &quot;phoenix&quot;</pre><pre>class Chat extends React.Component {<br>  componentDidMount() {<br>    let socket = new Socket(&quot;/socket&quot;, {params: {token: window.userToken}})</pre><pre>    socket.connect()</pre><pre>    let channel = socket.channel(&quot;room:lobby&quot;, {})</pre><pre>    channel.join()<br>      .receive(&quot;ok&quot;, response =&gt; { console.log(&quot;Joined successfully&quot;, response) })<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default Chat</pre><p>Notice that we are doing the following:</p><ul><li>Set <em>socket </em>to the endpoint as configured in lib/chat_app/endpoint.ex</li><li>Connect <em>socket</em></li><li>Store our channel in variable also called <em>channel</em></li><li>Join the channel log a successful response</li></ul><p>If we are able to join successfully, then we should have “Joined successfully” logged in our console.</p><p>Let’s run mix phoenix.server and check this out on <a href="http://localhost:4000/">http://localhost:4000/</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*sT6w78HSIUB2WACXjVCq4A.png" /></figure><p>Woot woot!</p><h4>Rendering User Messages</h4><p>Let’s add an input component and have our types messages render to the UI.</p><p>I’m once again going to be using <a href="http://bulma.io/">Bulma</a>. To configure Bulma, add the following snippet in the head of web/templates/layout/app.html.eex:</p><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;<br><a href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.5.0/css/bulma.css">https://cdnjs.cloudflare.com/ajax/libs/bulma/0.5.0/css/bulma.css</a>&quot;&gt;</pre><p>Back in our <em>Chat </em>component, let’s render an input and button element within a form:</p><pre>render() {<br>  return (<br>    &lt;div&gt;<br>      &lt;form onSubmit={this.handleSubmit.bind(this)} &gt;<br>      &lt;div className=&quot;field&quot;&gt;<br>        &lt;label<br>          className=&quot;label&quot;<br>          style={{<br>            textAlign: &quot;left&quot;<br>          }}<br>        &gt;<br>        GenericUsername:<br>        &lt;/label&gt;<br>        &lt;div className=&quot;control&quot;&gt;<br>          &lt;input<br>            className=&quot;input&quot;<br>            type=&quot;text&quot;<br>            style={{<br>              marginTop: &quot;10px&quot;<br>            }}<br>          /&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;button<br>        type=&quot;submit&quot;<br>        value=&quot;Submit&quot;<br>        className=&quot;button is-primary&quot;<br>        style={{<br>          marginTop: &quot;10px&quot;<br>        }}<br>      &gt;<br>        Submit<br>        &lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Let’s add a local state property called <em>inputMessage </em>that stores the current value of the input. We also need an event handler called <em>handleInputMessage </em>to update <em>inputMessage </em>on every change:</p><pre>class Chat extends React.Component {<br>  constructor() {<br>    super();<br>    this.state = {<br>      inputMessage: &quot;&quot;<br>    }<br>  }</pre><pre> //componentDidMount stuff</pre><pre>  handleInputMessage(event) {<br>    this.setState({<br>      inputMessage: event.target.value<br>    })<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;form onSubmit={this.handleSubmit.bind(this)} &gt;<br>        &lt;div className=&quot;field&quot;&gt;<br>          &lt;label<br>            className=&quot;label&quot;<br>            style={{<br>              textAlign: &quot;left&quot;<br>            }}<br>          &gt;<br>          GenericUsername:<br>          &lt;/label&gt;<br>          &lt;div className=&quot;control&quot;&gt;<br>            &lt;input<br>              className=&quot;input&quot;<br>              type=&quot;text&quot;<br>              style={{<br>                marginTop: &quot;10px&quot;<br>              }}<br>              value = {this.state.inputMessage}<br>              onChange = {this.handleInputMessage.bind(this)}<br>            /&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;button<br>          type=&quot;submit&quot;<br>          value=&quot;Submit&quot;<br>          className=&quot;button is-primary&quot;<br>          style={{<br>            marginTop: &quot;10px&quot;<br>          }}<br>        &gt;<br>          Submit<br>          &lt;/button&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    )<br>  }</pre><pre>export default Chat</pre><p>Notice that we also have onSubmit={this.handleSubmit.bind(this)} to handle a form submission. Let’s add that event handler:</p><pre>handleSubmit(event) {<br>  event.preventDefault();<br>  console.log(this.state.inputMessage);<br>}</pre><p>For now, it will just log the current input message so we can confirm everything is working so far.</p><p>Run brunch build and let’s check the local host:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68jomxblziRMfeJmE4xsUQ.png" /></figure><p>Sweet! Everything looks great at this point.</p><p>Next, we want the handleSubmit function to push submitted input messages to an array in our local state which we can call <em>userMessages</em>:</p><pre>constructor() {<br>  super();<br>  this.state = {<br>    inputMessage: &quot;&quot;,<br>    userMessages: []<br>  }<br>}</pre><pre>handleSubmit(event) {<br>  event.preventDefault();<br>  this.setState({<br>    userMessages: this.state.userMessages.concat(this.state.inputMessage)<br>  })<br>}</pre><p>Next, let’s render a presentational component for each message in <em>userMessages</em>:</p><pre>render() {<br>  const userMessages = this.state.userMessages.map((message, index) =&gt;<br>    &lt;UserMessage<br>      key = { index }<br>      username = { &quot;GenericUsername&quot; }<br>      message = { message }<br>    /&gt;<br>  );<br>  return (<br>    &lt;div&gt;<br>      //form here<br>      {userMessages}<br>    &lt;/div&gt;<br>  )<br>}</pre><p>We need to then make the <em>UserMessage </em>component. Create a file called <em>UserMessage.js </em>under the <em>presentationals folder </em>and let’s add the following:</p><pre>import React from &quot;react&quot;;</pre><pre>class UserMessage extends React.Component {</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;box&quot; style={{ marginBottom: &quot;10px&quot; }}&gt;<br>        &lt;article className=&quot;media&quot;&gt;<br>          &lt;div className=&quot;media-content&quot;&gt;<br>            &lt;div className=&quot;content&quot;&gt;<br>              &lt;p&gt;<br>                &lt;strong&gt;{this.props.username}&lt;/strong&gt;<br>                &lt;br/&gt;<br>                {this.props.message}<br>              &lt;/p&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/article&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default UserMessage</pre><p>Back in <em>Chat</em>, let’s import this component:</p><pre>import UserMessage from &#39;../presentationals/UserMessage&#39;;</pre><p>I’m also going to wrap the injected <em>UserMessage </em>components within a flexbox container:</p><pre>&lt;div<br>  className=&quot;flex-container&quot;<br>  style={{<br>    display: &quot;flex&quot;,<br>    flexDirection: &quot;column&quot;,<br>    alignItems: &quot;flexStart&quot;,<br>    justifyContent: &quot;flexStart&quot;,<br>    margin: &quot;auto&quot;,<br>    width: &quot;100%&quot;<br>  }}<br>&gt;<br>{userMessages}<br>&lt;/div&gt;</pre><p>Run brunch build and let’s check the local host:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HR8bRSFhCPXJWjky0Nm36g.png" /></figure><p>We can now see our messages rendering.</p><p>Really quickly, let’s improve the experience by emptying <em>inputMessage </em>on every submission:</p><pre>handleSubmit(event) {<br>  event.preventDefault();<br>  this.setState({<br>    userMessages: this.state.userMessages.concat(this.state.inputMessage),<br>    inputMessage: &quot;&quot;<br>  })<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQ0kZLA1H8bjLwMNX0x5Ew.png" /></figure><h4>Sending and Receiving Messages</h4><p>Currently, we are just rendering the values of the input to our UI. We aren’t pushing them out as messages via a channel.</p><p>First, let’s go to <em>Chat.js </em>and push <em>inputMessage </em>to the channel:</p><pre>handleSubmit(event) {<br>  event.preventDefault();<br>  channel.push(&quot;new_msg&quot;, {body: this.state.inputMessage})<br>  this.setState({<br>    userMessages: this.state.userMessages.concat(this.state.inputMessage),<br>    inputMessage: &quot;&quot;<br>  })<br>}</pre><p>channel.push(“new_msg”, {body: this.state.inputMessage}) consists of two main parts.</p><p>“new_msg” the string defining the <em>event name</em>.</p><p>{body: this.state.inputMessage} is the <em>payload</em> which contains the data.</p><p>We will now have to write the server-side code to handle this incoming event.</p><p>Open web/channels/room_channel.ex and add the following:</p><pre>defmodule ChatApp.RoomChannel do<br>  use Phoenix.Channel</pre><pre>  def join(&quot;room:lobby&quot;, _message, socket) do<br>    {:ok, socket}<br>  end</pre><pre>  def handle_in(&quot;new_msg&quot;, %{&quot;body&quot; =&gt; body}, socket) do<br>    broadcast socket, &quot;new_msg&quot;, %{body: body}<br>    {:noreply, socket}<br>  end</pre><pre>end</pre><p>We have added a function called handle_in which takes the payload (body) of the incoming message via the socket and broadcasts that message back.</p><p>Let’s finish up by adding the logic for our React frontend to receive the message broadcasted from the server and render it to the UI.</p><p>Open <em>Chat.js </em>and let’s add another array in our local state to keep track of these messages from the server:</p><pre>constructor() {<br>  super();<br>  this.state = {<br>    inputMessage: &quot;&quot;,<br>    userMessages: [],<br>    serverMessages: []<br>  }<br>}</pre><p>In componentWillMount(), let’s have the payload of the incoming “new_msg” message logged to the console:</p><pre>componentWillMount() {<br>  let socket = new Socket(&quot;/socket&quot;, {params: {token: window.userToken}})<br>  socket.connect()</pre><pre>  let channel = socket.channel(&quot;room:lobby&quot;, {})<br>  channel.join()<br>    .receive(&quot;ok&quot;, response =&gt; { console.log(&quot;Joined successfully&quot;, response) })</pre><pre>  channel.on(&quot;new_msg&quot;, payload =&gt; {<br>    console.log(payload);<br>  })<br>}</pre><p>If you run brunch build, you will see the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPrxLV4V9L6NYeeY8BBUqA.png" /></figure><p>The issue is that we are doing channel.push(..) in handleSubmit but channel is within the scope of componentWillMount(). To resolve this, let’s adjust the code in componentWillMount():</p><pre>class Chat extends React.Component {<br>  constructor() {<br>    super();<br>    this.state = {<br>      inputMessage: &quot;&quot;,<br>      userMessages: [],<br>      serverMessages: [],<br>    }</pre><pre>    let socket = new Socket(&quot;/socket&quot;, {params:<br>      {token: window.userToken}<br>    });<br>    socket.connect();</pre><pre>    this.channel = socket.channel(&quot;room:lobby&quot;, {});<br>  }</pre><pre>  componentWillMount() {<br>    this.channel.join()<br>      .receive(&quot;ok&quot;, response =&gt; { console.log(&quot;Joined successfully&quot;, response) })</pre><pre>    this.channel.on(&quot;new_msg&quot;, payload =&gt; {<br>      this.setState({<br>        serverMessages: this.state.serverMessages.concat(payload.body)<br>      })<br>    })<br>  }</pre><p>We have moved the channel configuration to the constructor and stored the channel in this.channel.</p><p>Now, we can just do this.channel whenever we want to reference our channel in our class. I already did this for componentWillMount() but let’s also do it for handleSumbit:</p><pre>handleSubmit(event) {<br>  event.preventDefault();<br>  this.channel.push(&quot;new_msg&quot;, {body: this.state.inputMessage})<br>  this.setState({<br>    userMessages: this.state.userMessages.concat(this.state.inputMessage),<br>    inputMessage: &quot;&quot;<br>  })<br>}</pre><p>Now, we can run brunch build with no issues. Try sending a message and check the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8z9O8Ejtqkp_MN1tRliYyA.png" /></figure><p>As expected, we have the payload is an object with a key called <em>body </em>and a value of “Can you hear me?”.</p><p>Awesome!</p><p>Let’s push the body value from the payload to the <em>serverMessages</em> array:</p><pre>this.channel.on(&quot;new_msg&quot;, payload =&gt; {<br>  this.setState({<br>    serverMessages: this.state.serverMessages.concat(payload.body)<br>  })<br>})</pre><p>Now, let’s render a component called <em>ServerMessage </em>for each message in the <em>serverMessages </em>array:</p><pre>render() {<br>  const userMessages = this.state.userMessages.map((message, index) =&gt;<br>    &lt;UserMessage<br>      key = { index }<br>      username = { &quot;GenericUsername&quot; }<br>      message = { message }<br>    /&gt;<br>  );</pre><pre>  const serverMessages = this.state.serverMessages.map((message, index) =&gt;<br>    &lt;ServerMessage<br>      key = { index }<br>      username = { &quot;Server&quot; }<br>      message = { message }<br>    /&gt;<br>  );</pre><p>Then, we inject this like so:</p><pre>{userMessages}<br>{serverMessages}</pre><p>Let’s create the <em>ServerMessage </em>component in a file called <em>ServerMessage.js </em>in the <em>presentationals </em>folder and the following:</p><pre>import React from &quot;react&quot;;</pre><pre>class ServerMessage extends React.Component {</pre><pre>  render() {<br>    return (<br>      &lt;div className=&quot;box&quot; style={{ marginBottom: &quot;10px&quot; }}&gt;<br>        &lt;article className=&quot;media&quot;&gt;<br>          &lt;div className=&quot;media-content&quot;&gt;<br>            &lt;div className=&quot;content&quot;&gt;<br>              &lt;p&gt;<br>                &lt;strong&gt;{this.props.username}&lt;/strong&gt;<br>                &lt;br/&gt;<br>                {this.props.message}<br>              &lt;/p&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/article&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default ServerMessage</pre><p>Just like <em>UserMessage</em>, we are taking the passed down props to present the message within a box defined by Bulma.</p><p>Lastly, let’s import this component in <em>Chat.js</em>:</p><pre>import ServerMessage from &#39;../presentationals/ServerMessage&#39;;</pre><p>Run brunch build and test this out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgJ5A3k34XCIBJ0qsKhIrA.gif" /><figcaption>Chat With Phoenix Test</figcaption></figure><p>Cool beans!</p><p>There’s just one issue. Multiple user messages skew the correct order of the rendered boxes in our UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9KwSluheeaTUD8qTgDP7A.png" /></figure><p>This is because of the fact that we are injecting the user messages and server messages separately:</p><pre>{userMessages}<br>{serverMessages}</pre><p>To correct this, we need to just nest one single collection of messages.</p><p>First, let’s change our local state to just have one array called <em>messages</em>:</p><pre>this.state = {<br>  inputMessage: &quot;&quot;,<br>  messages: []<br>}</pre><p>Delete <em>userMessages</em> and <em>serverMessages </em>above the return in our render and use find and replace to update every use of userMessages and serverMessages to just messages.</p><p>Then, we can map through <em>messages </em>and render the right component based on the index:</p><pre>const messages = this.state.messages.map((message, index) =&gt; {<br>  if(index % 2 == 0) {<br>    return (<br>      &lt;UserMessage<br>        key = { index }<br>        username = { &quot;GenericUsername&quot; }<br>        message = { message }<br>      /&gt;<br>    )<br>  } else {<br>    return (<br>      &lt;ServerMessage<br>        key = { index }<br>        username = { &quot;Server&quot; }<br>        message = { message }<br>      /&gt;<br>    )<br>  }<br>});</pre><p>Lastly, we can inject messages:</p><pre>{messages}</pre><p>Now, our messages are alternating in the correct order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vD8Hf5yzjzV_0MaH-Zh0Ig.png" /></figure><p>That’s all she wrote!</p><p>💪 🔥 💚 🙌 ✋</p><h3>Final Code</h3><p><a href="https://github.com/michaelmang/full-stack-react-phoenix/tree/master/chat_app">Available on GitHub.</a></p><h3>Concluding Thoughts</h3><p>After doing writing tutorials on all sorts of technology for the past year, I’ve realized that it’s best to teach fundamentals in simple, small projects and leave it up to you to do the more advanced examples.</p><p>With that being said, I think this chat app was quite simple but also quite helpful for learning how to work with channels in Phoenix. For a challenge, try to see how you can creatively use real-time messaging in your own project. A fun idea would to make a simple chat bot where the server responds to specific phrases differently.</p><p>With channels covered, there is one final chapter for this book where we will wrap things up.</p><h3>Final Chapter</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-10-moving-forward-69303b6b75b0">The final chapter is now available.</a></p><h3>Sign Up for Notifications</h3><p><a href="http://codingartist.io/full-stack-react-phoenix/">Get notified when each chapter is released.</a></p><p>Cheers,<br>Mike Mangialardi<br>Founder of Coding Artist</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=245a24647e84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-9-channels-245a24647e84">Full-Stack React With Phoenix (Chapter 9 | Channels)</a> was originally published in <a href="https://medium.com/coding-artist">Coding Artist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack React With Phoenix (Chapter 8 | User Authentication)]]></title>
            <link>https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-8-user-authentication-fb1ff48a5e51?source=rss----6df8bca0c0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/fb1ff48a5e51</guid>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Michael Mangialardi]]></dc:creator>
            <pubDate>Wed, 02 Aug 2017 18:34:40 GMT</pubDate>
            <atom:updated>2017-08-05T19:14:29.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-g8Mkgvq4JmjlQChMj-75A.png" /></figure><h3>Table of Contents</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Chapter 1 | Why Bother?</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Chapter 2 | Learning the Basics of Elixir</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4">Chapter 3 | Introduction to Phoenix</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-4-implementing-react-716979133669">Chapter 4 | Implementing React</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-5-working-with-postgresql-83ec4f3286b2">Chapter 5 | Working With PostgreSQL</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-6-creating-a-postgresql-api-service-9f2775161d3f">Chapter 6 | Creating a PostgreSQL API Service</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-7-crud-operations-79d4e5af9a0d">Chapter 7 | CRUD Operations</a></p><h3>Scope of This Chapter</h3><p>In the previous chapter, we were able to create an API service with Phoenix. This is at the heart of full-stack development. However, we didn’t cover the critical use case of doing user authentication. We will be doing another mini-project so cover how to do this.</p><h3>Getting Started</h3><p>While I could just provide a template, let’s walk through the creation of our new project for extra practice.</p><h4>Setup</h4><p>First, let’s create a new project called <em>phoenix_user_authenticaion </em>and enter the directory:</p><pre>mix phoenix.new phoenix_user_authentication<br>cd phoenix_user_authentication</pre><p>Next, go ahead and open the project in a code editor of choice. Check the configuration the PostgreSQL database that we will create in <em>config/dev.exs.</em></p><p>Here is my configuration:</p><pre># Configure your database<br>config :phoenix_user_authentication, PhoenixUserAuthentication.Repo,<br>  adapter: Ecto.Adapters.Postgres,<br>  username: &quot;postgres&quot;,<br>  password: &quot;postgres&quot;,<br>  database: &quot;phoenix_user_authentication_dev&quot;,<br>  hostname: &quot;localhost&quot;,<br>  pool_size: 10,<br>  port: 5432 # I added this, 5432 is default</pre><p>If it looks good, go ahead and run mix ecto.create to create this database.</p><p>If you open pgAdmin and refresh our <em>Phoenix </em>server, you can double-click on the database and connect to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*tgB1H_KAasDfPpTwOCR-3w.png" /></figure><p>Cool.</p><h4>Creating a Users Table</h4><p>We want to create a table in our database to store users:</p><pre>Users <br>_____<br>    <br>    username | password_hash</pre><pre>1</pre><pre>2</pre><pre>3</pre><pre>...</pre><p>We will make this really simple and only store a <em>username </em>and <em>password_hash </em>(encrypted password) field within a table called <em>Users</em>.</p><p>Let’s go ahead and create a model for this table under <em>web/models</em> and name it <em>users.ex</em>:</p><pre>defmodule PhoenixUserAuthentication.Users do<br>  use PhoenixUserAuthentication.Web, :model<br>  schema &quot;users&quot; do<br>    field :username, :string<br>    field :password_hash, :string<br>    timestamps()<br>  end</pre><pre>end</pre><p>Now, we can run mix ecto.gen.migration users to create the boilerplate for a migration file for our <em>users </em>table.</p><p>Now, open up the generated migration file found under <em>priv/repo/migrations</em>:</p><pre>defmodule PhoenixUserAuthentication.Repo.Migrations.Users do<br>  use Ecto.Migration</pre><pre>  def change do</pre><pre>  end<br>end</pre><p>Recall, migration files used to create tables in a database following the shape specified in a schema. Therefore, let’s update the change function like so:</p><pre>defmodule PhoenixUserAuthentication.Repo.Migrations.Users do<br>  use Ecto.Migration</pre><pre>  def change do<br>    create table(:users) do<br>      add :username, :string, null: false<br>      add :password_hash, :string, null: false<br>      timestamps()<br>    end<br>  end</pre><pre>end</pre><p>We add create table(:users) which is a function to create a table called <em>users </em>and adds a <em>username </em>and <em>password_hash </em>file with their type. I also included null: false as these fields can’t be null.</p><p>We are now ready to execute our migration to create our <em>users </em>table in our database by running the following:</p><pre>mix ecto.migrate</pre><p>Let’s see if it worked!</p><p>Refresh our Phoenix server in pgAdmin:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*nhbDmaG3y4h9AzVBd-5tuw.png" /></figure><p>Expand our schema under <em>Databases/phoenix_user_authentication_dev/schemas/public:</em></p><p>Underneath <strong>tables</strong>, we can see that the <em>users </em>table and a table with meta data of our migrations were both added:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*DPcWwfUZ-yDx0zfGlLEV1Q.png" /></figure><p>If we view the <em>users </em>table, we can see our table has the fields as specified in our schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05z2xsas7Z92xqFCHXI3WQ.png" /></figure><p>Awesome!</p><p>We need to make two quick edits before we manually enter in a row.</p><p>We need our timestamp columns (<em>inserted_at</em> and <em>updated_at</em>) to be populated automatically using the following sql expression: now()</p><p>Right-click <strong>inserted_at </strong>and click <strong>properties</strong>.</p><p>Select the <strong>definition </strong>tab and add now() as the default value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*peEaoX6PMF9MGIZzC0Uikg.png" /></figure><p>Repeat this same process for <strong>updated_at</strong>.</p><h4>Creating Our API Service</h4><p>Before we get into the user authentication stuff, let’s go ahead and setup a basic api service for fetching all users and creating a new user.</p><p>Open <em>web/router.ex </em>and let’s add the HTTP request type, route, controller, and function to call within the controller for each of our interactions:</p><pre>scope &quot;/api&quot;, PhoenixUserAuthentication do<br>  pipe_through :api</pre><pre>  get &quot;/users&quot;, UsersController, :index<br>  post &quot;/users&quot;, UsersController, :create</pre><pre>end</pre><p>We want the <em>/api </em>route to pass through our api pipeline. On the scope of the <em>/api </em>path, we will have <em>/users</em>.</p><p><em>/api/users </em>will handle a GET and POST request. On a GET request, the <em>index </em>function will be called within <em>UsersController</em>. On a POST request, the <em>create </em>function will be called within the <em>UsersController</em>.</p><p>Next, let’s create a file called <em>users_controller.ex </em>within the <em>controllers </em>folder for our <em>UsersController</em>.</p><p>The shell of our code looks like this:</p><pre>defmodule PhoenixUserAuthentication.UsersController do<br>  use PhoenixUserAuthentication.Web, :controller</pre><pre>  alias PhoenixUserAuthentication.Users</pre><pre>  def index(conn, _params) do<br>    # get all users</pre><pre>    # render JSON object containing all users<br>  end</pre><pre>  def create(conn, %{&quot;users&quot; =&gt; users_params}) do<br>    # create changeset</pre><pre>    # use changeset to insert a new row using params<br>  end</pre><pre>end</pre><p>We create an alias so we don’t have to write out PhoenixUserAuthentication.Users when referencing the <em>Users </em>table.</p><p>Then, we have the shell of the <em>index</em> and <em>create </em>functions.</p><p>The <em>index </em>function will use Repo.all to fetch all rows in the <em>Users </em>table and invoke the rendering of a JSON object containing those users:</p><pre>def index(conn, _params) do<br>  users= Repo.all(Users)<br>  render conn, &quot;index.json&quot;, users: users<br>end</pre><p>The <em>create </em>function will get a changeset which can be used to insert a new row into the <em>Users </em>table The changeset will be created using parameters from the HTTP request.</p><pre>def create(conn, %{&quot;users&quot; =&gt; users_params}) do<br>  changeset = Users.changeset(%Users{}, users_params)</pre><pre>  case Repo.insert(changeset) do<br>    {:ok, _blogs} -&gt;<br>      users = Repo.all(Users)<br>      render conn, &quot;index.json&quot;, users: users<br>  end<br>end</pre><p>On a successful insertion, all of the users will be rendered so we can see the added user.</p><p>Since we reference the changeset here, let’s create that next.</p><p>The <em>changeset</em> function will go in our model found in <em>web/models/users.ex</em>:</p><pre>defmodule PhoenixUserAuthentication.Users do<br>  use PhoenixUserAuthentication.Web, :model<br>  schema &quot;users&quot; do<br>    field :username, :string<br>    field :password_hash, :string<br>    timestamps()<br>  end</pre><pre>  def changeset(struct, params) do<br>    struct<br>    |&gt; cast(params, [:username, :password_hash])<br>    |&gt; validate_required([:username, :password_hash])<br>    |&gt; unique_constraint(:username)<br>  end</pre><pre>end</pre><p>The <em>changeset</em> function takes an empty struct and casts the parameters and validates the required fields. In addition, it makes sure the usernames stay unique.</p><p>We will have to add more for our user authentication stuff but let’s leave it be for now.</p><p>To finish up our API service without user authentication stuff, let’s create the view to render a JSON object with all the users.</p><p>Create a new file called <em>users_view.ex </em>in <em>web/views.</em></p><pre>defmodule PhoenixUserAuthentication.UsersView do<br>  use PhoenixUserAuthentication.Web, :view</pre><pre>  #show multiple users<br>  def render(&quot;index.json&quot;, %{users: users}) do<br>    %{<br>      users: Enum.map(users, &amp;users_json/1)<br>    }<br>  end</pre><pre>  def users_json(user) do<br>    %{<br>      username: user.username<br>    }<br>  end</pre><pre>end</pre><p>Here, we render a JSON object called <em>index </em>that will ultimately contain an array called <em>users</em> that has an object containing the information for each user in every index.</p><h3>Password Hashing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ppiAt8MO4QzgmjoOhCLjzw.png" /></figure><p>I’ve mentioned that we have to do user authentication <em>stuff</em>. You may be thinking: “What kind of stuff do we need to do?”</p><p>When working with passwords of users, we don’t want to store the exact password as a string within the database for security reasons. Instead, we need to hash the password. Hashing a password means taking the password string and applying an algorithm that will generate a completely different value.</p><p>The hashed value will be the same every time, so you can store the hashed password in a database and check the user’s entered password to the stored hash. [<a href="https://stackoverflow.com/questions/1602776/what-is-password-hashing">1</a>]</p><p>With Phoenix, we can use a password hashing library called <a href="https://hexdocs.pm/comeonin/Comeonin.html#content">Comeonin</a>.</p><p>We need to add this as a dependency in <em>mix.exs </em>(the Elixir equivalent of <em>package.json</em>). This will occur in two places.</p><p>First, we add it in the <em>application </em>function:</p><pre>def application do<br>  [mod: {PhoenixUserAuthentication, []},<br>   applications: [<br>     :phoenix, :phoenix_pubsub, <br>     :phoenix_html, :cowboy, :logger, :gettext,<br>     :phoenix_ecto, :postgrex, :comeonin<br>   ]<br>  ] #comeonin added here<br>end</pre><p>We also add it our <em>deps</em>:</p><pre>defp deps do<br>  [{:phoenix, &quot;~&gt; 1.2.4&quot;},<br>   {:phoenix_pubsub, &quot;~&gt; 1.0&quot;},<br>   {:phoenix_ecto, &quot;~&gt; 3.0&quot;},<br>   {:postgrex, &quot;&gt;= 0.0.0&quot;},<br>   {:phoenix_html, &quot;~&gt; 2.6&quot;},<br>   {:phoenix_live_reload, &quot;~&gt; 1.0&quot;, only: :dev},<br>   {:gettext, &quot;~&gt; 0.11&quot;},<br>   {:cowboy, &quot;~&gt; 1.0&quot;},<br>   {:comeonin, &quot;~&gt; 2.6&quot;}<br> ]<br>end</pre><p>Let’s install this new dependency using mix deps.get.</p><p>With <em>Comeonin</em> installed, we can go back to our model in <em>web/models/user.ex</em>.</p><p>We want to add a virtual password which means we can use this field in our model without it being stored in our database:</p><pre>schema &quot;users&quot; do<br>  field :username, :string<br>  field :password_hash, :string<br>  field :password, :string, virtual: true<br>  timestamps()<br>end</pre><p>We also update <em>changeset</em> to validate the username and password then hash the password by calling put_password_hash:</p><pre>def changeset(struct, params) do<br>    struct<br>    |&gt; cast(params, [:username, :password])<br>    |&gt; validate_required([:username, :password])<br>    |&gt; unique_constraint(:username)<br>    |&gt; validate_length(:password, min: 6, max: 100)<br>    |&gt; put_password_hash<br>  end</pre><p>put_password_hash will check apply a hash to the password in the changeset using Comeonin.Bcrypt.hashpwsalt:</p><pre>defp put_password_hash(changeset) do<br>  case changeset do<br>    %Ecto.Changeset{valid?: true, changes: %{password: password}} -&gt;<br>      put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(password))<br>    _ -&gt;<br>      changeset<br>  end<br>end</pre><p>Now, this line in the <em>create </em>function of our <em>UsersController </em>will return a username and hashed password to insert into our database:</p><pre>changeset = Users.changeset(%Users{}, users_params)</pre><p>Let’s create a React frontend with a signup form to make sure our database is adding new users via our API.</p><h3>Creating a Signup Form</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjRBWel-2E8nwdD0nr0TDw.png" /></figure><p>We’ve already created a form in a React frontend and gone over all the setup. Again, I will repeat this in place of providing a template for extra practice.</p><p>First, we can install our main dependencies:</p><pre>npm install --save react react-dom react-router-dom babel-preset-react axios</pre><p>Next, we configure our <em>brunch-config.js </em>file to apply presets for Babel and React:</p><pre>plugins: {<br>  babel: {<br>    presets: [&quot;es2015&quot;, &quot;react&quot;],<br>    // Do not use ES6 compiler in vendor code<br>    ignore: [/web\/static\/vendor/]<br>  }<br>},</pre><p>In addition, we add a whitelist in under the <em>npm </em>options in this file so that it is clear that we are going to use <em>react</em> and <em>react-dom</em>:</p><pre>npm: {<br>  enabled: true,<br>  whitelist: [&quot;phoenix&quot;, &quot;phoenix_html&quot;, &quot;react&quot;, &quot;react-dom&quot;]<br>}</pre><p>We can then create the target for our app in the <em>index.html.eex </em>template (delete everything else):</p><pre>&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;</pre><p>The app template contains a pre-populated header which we can remove:</p><pre>&lt;header class=&quot;header&quot;&gt;<br>  &lt;nav role=&quot;navigation&quot;&gt;<br>    &lt;ul class=&quot;nav nav-pills pull-right&quot;&gt;<br>      &lt;li&gt;&lt;a href=&quot;<a href="http://www.phoenixframework.org/docs">http://www.phoenixframework.org/docs</a>&quot;&gt;Get Started&lt;/a&gt;&lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/nav&gt;<br>  &lt;span class=&quot;logo&quot;&gt;&lt;/span&gt;<br>&lt;/header&gt;</pre><pre>^^^ delete this</pre><p>In web/static/js, let’s make a complete React project directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*nCvpiFjUESEVCW0MAlkY-A.png" /></figure><p>We just add <em>containers </em>and <em>presentationals </em>folders. <em>Containers </em>refer to active components where the API request will be made and the retrieved data will be passed down to a <em>presentational </em>component which presents something to our UI using the inherited props.</p><p>Open <em>app.js</em> and let’s add the following code:</p><pre>import &quot;phoenix_html&quot;;<br>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br>import { BrowserRouter as Router, Route, Link } from &#39;react-router-dom&#39;;<br>import Signup from &quot;./containers/Signup&quot;;</pre><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;div&gt;<br>          &lt;Route exact path=&quot;/&quot; component={Signup}/&gt;<br>        &lt;/div&gt;<br>      &lt;/Router&gt;<br>    )<br>  }<br>}</pre><pre>ReactDOM.render(<br>  &lt;App/&gt;,<br>  document.getElementById(&quot;app&quot;)<br>)</pre><p>In the code above, we are going to display a signup container on the default path for now. Let’s create this container.</p><p>Create a file called <em>Signup.js </em>under the <em>containers </em>folder:</p><pre>import React from &quot;react&quot;;<br>import axios from &quot;axios&quot;;</pre><pre>class Signup extends React.Component {<br>  constructor() {<br>    super();<br>    this.state = {<br>      username: &#39;&#39;,<br>      password: &#39;&#39;<br>    };<br>  }</pre><pre>  handleUsername(event) {<br>    this.setState({ username: event.target.value })<br>  }</pre><pre>  handlePassword(event) {<br>    this.setState({ password: event.target.value })<br>  }</pre><pre>  handleSubmit (event) {<br>    event.preventDefault();<br>    console.log(this.state);<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;form onSubmit={this.handleSubmit.bind(this)}&gt;<br>        &lt;div className=&quot;field&quot;&gt;<br>          &lt;label className=&quot;label&quot;&gt;Username&lt;/label&gt;<br>          &lt;div className=&quot;control&quot;&gt;<br>            &lt;input<br>              className=&quot;input&quot;<br>              type=&quot;text&quot;<br>              value = {this.state.username}<br>              onChange = {this.handleUsername.bind(this)}<br>            /&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;</pre><pre>        &lt;div className=&quot;field&quot;&gt;<br>          &lt;label className=&quot;label&quot;&gt;Password&lt;/label&gt;<br>          &lt;div className=&quot;control&quot;&gt;<br>            &lt;input<br>              className=&quot;input&quot;<br>              type=&quot;text&quot;<br>              value = {this.state.password}<br>              onChange = {this.handlePassword.bind(this)}<br>            /&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;</pre><pre>        &lt;button<br>          type=&quot;submit&quot;<br>          value=&quot;Submit&quot;<br>          className=&quot;button is-primary&quot;<br>        &gt;<br>        Submit<br>        &lt;/button&gt;</pre><pre>      &lt;/form&gt;<br>    )<br>  }<br>}</pre><pre>export default Signup</pre><p>The code above is just like the form we created in the previous chapter. It is using <a href="http://bulma.io/">Bulma</a> for predefined form styling and managing the values of each input via event handlers that update the local state.</p><p>Let’s try this signup form which currently will just log the local state on a submission.</p><p>Before we do that, however, let’s quickly add a CDN within the head of <em>web/templates/app.html.eex</em>:</p><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;<a href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.4/css/bulma.css">https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.4/css/bulma.css</a>&quot;&gt;</pre><p>Now, run brunch build and mix phoenix.server then go to <a href="http://localhost:4000/">http://localhost:4000/</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IdrA6X-4PQhrPEhtVkM6Gg.png" /></figure><p>Insert a username and password and hit submit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*__oAoOHBJHbIYhad6uj56w.png" /></figure><p>As expected, the username and password inputs are being stored in the local state.</p><p>Let’s update the handleSubmit event handler in the <em>Signup</em> container found in <em>Signup.js</em>:</p><pre>handleSubmit (event) {<br>  event.preventDefault();<br>  axios({<br>    method: &#39;post&#39;,<br>    headers: {&quot;Content-Type&quot;: &quot;application/json&quot;},<br>    url: &#39;<a href="http://localhost:4000/api/users&#39;">http://localhost:4000/api/users&#39;</a>,<br>    data: {<br>      users: {<br>        username: this.state.username,<br>        password: this.state.password<br>      }<br>    }<br>  });<br>}</pre><p>We replace the log to our console with some axios code to make the HTTP POST request on http://localhost:4000/api/users with parameters in the body.</p><p>Run brunch build and submit a new username and password from the form.</p><p>Now, we can refresh and view our <em>users </em>table to see the new row with a hashed password:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAG_t4GLyVLWpP8nYEBDrg.png" /></figure><p>Sweet! Next, we will create the login form and compare the inputs with the database to authenticate a user.</p><h3>User Authentication at Login</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOlhPFELmaK33rhBkOiRWA.png" /></figure><h4>Creating a Login Form in React</h4><p>Open <em>web/static/js/app.js </em>and let’s update it:</p><pre>import Signup from &quot;./containers/Signup&quot;;<br>import Login from &quot;./containers/Login&quot;;</pre><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;div&gt;<br>          &lt;Route exact path=&quot;/&quot; component={Signup}/&gt;<br>          &lt;Route path=&quot;/login&quot; component={Login}/&gt;<br>        &lt;/div&gt;<br>      &lt;/Router&gt;<br>    )<br>  }<br>}</pre><p>We have imported a new container component called <em>Login </em>and added a route for it.</p><p>Create <em>Login.js </em>in the <em>containers</em> folder to define this component:</p><pre>import React from &quot;react&quot;;<br>import axios from &quot;axios&quot;;</pre><pre>class Login extends React.Component {<br>  constructor() {<br>    super();<br>    this.state = {<br>      username: &#39;&#39;,<br>      password: &#39;&#39;<br>    };<br>  }</pre><pre>  handleUsername(event) {<br>    this.setState({ username: event.target.value })<br>  }</pre><pre>  handlePassword(event) {<br>    this.setState({ password: event.target.value })<br>  }</pre><pre>  handleSubmit (event) {<br>    event.preventDefault();<br>    //authenticate user<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;form onSubmit={this.handleSubmit.bind(this)}&gt;<br>        &lt;div className=&quot;field&quot;&gt;<br>          &lt;label className=&quot;label&quot;&gt;Username&lt;/label&gt;<br>          &lt;div className=&quot;control&quot;&gt;<br>            &lt;input<br>              className=&quot;input&quot;<br>              type=&quot;text&quot;<br>              value = {this.state.username}<br>              onChange = {this.handleUsername.bind(this)}<br>            /&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;</pre><pre>        &lt;div className=&quot;field&quot;&gt;<br>          &lt;label className=&quot;label&quot;&gt;Password&lt;/label&gt;<br>          &lt;div className=&quot;control&quot;&gt;<br>            &lt;input<br>              className=&quot;input&quot;<br>              type=&quot;text&quot;<br>              value = {this.state.password}<br>              onChange = {this.handlePassword.bind(this)}<br>            /&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;</pre><pre>        &lt;button<br>          type=&quot;submit&quot;<br>          value=&quot;Submit&quot;<br>          className=&quot;button is-primary&quot;<br>        &gt;<br>        Submit<br>        &lt;/button&gt;</pre><pre>      &lt;/form&gt;<br>    )<br>  }<br>}</pre><pre>export default Login</pre><p>This form is just like our signup form except we need to do something else on a submission:</p><pre>handleSubmit (event) {<br>  event.preventDefault();<br>  //authenticate user<br>}</pre><p>Let’s also add a button to link to the login form from the signup form by adding the following to <em>Signup.js</em>:</p><pre>import React from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br>import { Link } from &#39;react-router-dom&#39;;</pre><pre>class Signup extends React.Component {<br>  constructor() {<br>    super();<br>    this.state = {<br>      username: &#39;&#39;,<br>      password: &#39;&#39;<br>    };<br>  }</pre><pre>  handleUsername(event) {<br>    this.setState({ username: event.target.value })<br>  }</pre><pre>  handlePassword(event) {<br>    this.setState({ password: event.target.value })<br>  }<br>  <br>  handleSubmit (event) {<br>    event.preventDefault();<br>    // authenticate user<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;form onSubmit={this.handleSubmit.bind(this)}&gt;<br>          &lt;div className=&quot;field&quot;&gt;<br>            &lt;label className=&quot;label&quot;&gt;Username&lt;/label&gt;<br>            &lt;div className=&quot;control&quot;&gt;<br>              &lt;input<br>                className=&quot;input&quot;<br>                type=&quot;text&quot;<br>                value = {this.state.username}<br>                onChange = {this.handleUsername.bind(this)}<br>              /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div className=&quot;field&quot;&gt;<br>            &lt;label className=&quot;label&quot;&gt;Password&lt;/label&gt;<br>            &lt;div className=&quot;control&quot;&gt;<br>              &lt;input<br>                className=&quot;input&quot;<br>                type=&quot;text&quot;<br>                value = {this.state.password}<br>                onChange = {this.handlePassword.bind(this)}<br>              /&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;button<br>            type=&quot;submit&quot;<br>            value=&quot;Submit&quot;<br>            className=&quot;button is-primary&quot;<br>          &gt;<br>          Submit<br>          &lt;/button&gt;<br>        &lt;/form&gt;<br>        &lt;Link<br>          className=&quot;button is-info&quot;<br>          to=&quot;/login&quot;<br>        &gt;<br>        Login<br>        &lt;/Link&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}<br>export default Signup</pre><p>We now have our signup and login forms rendering and routing correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEP_-NaWa0_nbZxN6T606Q.gif" /></figure><p><strong>Editorial Note: </strong>I made some slight changes after this screenshot so styling of buttons will be slightly different.</p><p>Next, we need to add the functionality of authenticating a user on login by comparing the username and password with the username and password hash in the database.</p><h4>Authentication Using Guardian</h4><p>To do this, we are going to use a library called <a href="https://github.com/ueberauth/guardian">Guardian</a>.</p><p>First, we need to add Guardian to our application and as a dependency in <em>mix.exs</em>:</p><pre>def application do<br>  [mod: {PhoenixUserAuthentication, []},<br>   applications: [<br>     :phoenix, :phoenix_pubsub,<br>     :phoenix_html, :cowboy, :logger, :gettext,<br>     :phoenix_ecto, :postgrex, :comeonin, :guardian<br>   ]<br>  ] <br>end</pre><pre>defp deps do<br>  [{:phoenix, &quot;~&gt; 1.3.0-rc&quot;},<br>   {:phoenix_pubsub, &quot;~&gt; 1.0&quot;},<br>   {:phoenix_ecto, &quot;~&gt; 3.0&quot;},<br>   {:postgrex, &quot;&gt;= 0.0.0&quot;},<br>   {:phoenix_html, &quot;~&gt; 2.6&quot;},<br>   {:phoenix_live_reload, &quot;~&gt; 1.0&quot;, only: :dev},<br>   {:gettext, &quot;~&gt; 0.11&quot;},<br>   {:cowboy, &quot;~&gt; 1.0&quot;},<br>   {:comeonin, &quot;~&gt; 2.6&quot;},<br>   {:guardian, &quot;~&gt; 0.14&quot;}<br> ]<br>end</pre><p>Then, we get this dependency by running:</p><pre>mix deps.get</pre><p>Open <em>config/config.exs </em>and let’s add some configuration code:</p><pre># Configures Guardian<br>config :guardian, Guardian,<br>  issuer: &quot;PhoenixUserAuthentication&quot;,<br>  ttl: {30, :days},<br>  verify_issuer: true,<br>  serializer: PhoenixUserAuthentication.GuardianSerializer</pre><p>We also need to add a secret key which we can generate using mix phoenix.gen.secret:</p><pre># Configures Guardian<br>config :guardian, Guardian,<br>  issuer: &quot;PhoenixUserAuthentication&quot;,<br>  ttl: {30, :days},<br>  verify_issuer: true,<br>  serializer: PhoenixUserAuthentication.GuardianSerializer,<br>  secret_key: &quot;syR5soTnDOp25yxyU4Y4rL/r0j4v/MNy/5l2gnjRcMwCx/UlWO88C28lWI0UrgJP&quot;</pre><pre># update for your generated secret key</pre><p>If you are curious about this configuration, you can check the <a href="https://github.com/ueberauth/guardian">official documentation</a>. The only thing that concerns us at the moment is to create the serializer which we specified at PhoenixUserAuthentication.GuardianSerializer.</p><p>Create a new file at <em>lib/phoenix_user_authentication </em>called <em>guardian_serializer.ex</em>:</p><pre>defmodule PhoenixUserAuthentication.GuardianSerializer do<br>  <a href="http://twitter.com/behaviour">@behaviour</a> Guardian.Serializer</pre><pre>  alias PhoenixUserAuthentication.Repo<br>  alias PhoenixUserAuthentication.Users</pre><pre>  def for_token(users = %Users{}), do: {:ok, &quot;Users:#{users.id}&quot;}<br>  def for_token(_), do: {:error, &quot;Unknown resource type&quot;}</pre><pre>  def from_token(&quot;Users:&quot; &lt;&gt; id), do: {:ok, Repo.get(Users, String.to_integer(id))}<br>  def from_token(_), do: {:error, &quot;Unknown resource type&quot;}<br>end</pre><p>Guardian uses <a href="https://jwt.io/">JSON web tokens</a> to perform authentication. I highly recommend reading an introduction on JSON web tokens <a href="https://jwt.io/introduction/">here</a>.</p><p>At a high level, you can think of possessing a token as authenticating a user during a session and allowing them access to our application. This is similar to possessing a token to have access to play arcade games. The code above can be thought of as giving and removing a token for a single user.</p><p>We need to keep track of a user’s possession of a token in a session at different points of our application. In our case, this will be logging in and logging out. To do this, we will use a separate controller called <em>SessionsController </em>with different functions to do things on those different points of our application.</p><p>To trigger these functions in <em>SessionsController</em>, we need to add some API routes which we can do in <em>web/router.ex</em>:</p><pre>scope &quot;/api&quot;, PhoenixUserAuthentication do<br>  pipe_through :api</pre><pre>  post &quot;/sessions&quot;, SessionsController, :create # login<br>  delete &quot;/sessions&quot;, SessionsController, :delete # log out</pre><pre>  get &quot;/users&quot;, UsersController, :index<br>  post &quot;/users&quot;, UsersController, :create</pre><pre>end</pre><p>We also need to add some plugs to our <em>api </em>pipeline:</p><pre>pipeline :api do<br>  plug :accepts, [&quot;json&quot;]<br>  plug Guardian.Plug.VerifyHeader, realm: &quot;Bearer&quot;<br>  plug Guardian.Plug.LoadResource<br>end</pre><p>plug Guardian.Plug.VerifyHeader, realm: “Bearer” looks for a token in the header and validates it. If there is a token, the user will be loaded so we can check permissions and authenticate accordingly from <em>SessionsController</em>. If a token can’t be verified, nothing happens.</p><p>Let’s start to write the functions within <em>SessionsController </em>as we specified in our <em>/sessions </em>routes for authenticating at login and logout.</p><p>Create a file called <em>session_controller.ex</em> under <em>web/controllers</em>.</p><p>First, we can add the create function:</p><pre>defmodule PhoenixUserAuthentication.SessionsController do<br>  use PhoenixUserAuthentication.Web, :controller</pre><pre>  alias PhoenixUserAuthentication.Users</pre><pre>  def create(conn, %{&quot;username&quot; =&gt; username, &quot;password&quot; =&gt; password}) do<br>    case authenticate(%{&quot;username&quot; =&gt; username, &quot;password&quot; =&gt; password}) do<br>      {:ok, user} -&gt;<br>        new_conn = Guardian.Plug.api_sign_in(conn, user, :access)<br>        jwt = Guardian.Plug.current_token(new_conn)</pre><pre>        new_conn<br>        |&gt; put_status(:created)<br>      :error -&gt;<br>        conn<br>        |&gt; put_status(:unauthorized)<br>    end<br>  end</pre><pre>  defp authenticate(%{&quot;username&quot; =&gt; username, &quot;password&quot; =&gt; password}) do<br>    user = Repo.get_by(Users, username: username)</pre><pre>    case check_password(user, password) do<br>      true -&gt; {:ok, user}<br>      _ -&gt; :error<br>    end<br>  end</pre><pre>  defp check_password(nil, _), do: Comeonin.Bcrypt.dummy_checkpw()<br>  defp check_password(user, password) do<br>    Comeonin.Bcrypt.checkpw(password, user.password_hash)<br>  end</pre><pre>end</pre><p>When a POST HTTP request is made on the <em>/api/sessions </em>route (which will occur on a submission from our login form), we call a function called <em>authenticate </em>which gets a user row by username using the username parameter and checks the password parameter with the stored password. If there’s a match, then {:ok, user} is returned.</p><p>On a return of {:ok, user}, we create a new connection where the user is authenticated via Guardian.Plug.api_sign_in(conn, user, :access). We also get the current JSON web token. We then put a <a href="https://hexdocs.pm/plug/Plug.Conn.Status.html">status</a> of “created”. On the case of an error, we put a status of “unauthorized”.</p><p>When a user logs out and a DELETE HTTP request is made on the <em>/api/sessions </em>route, we want to revoke the token that is granting them access:</p><pre>def delete(conn, _params) do<br>  jwt = Guardian.Plug.current_token(conn)<br>  Guardian.revoke(jwt)</pre><pre>  conn<br>  |&gt; put_status(:ok)<br>end</pre><p>When a sign up occurs via a POST HTTP request on <em>/api/users</em>, we want to also authenticate the user so they don’t have to login. Therefore, let’s update our <em>create </em>function in <em>users_controller.ex</em>:</p><pre>def create(conn, %{&quot;users&quot; =&gt; users_params}) do<br>  changeset = Users.changeset(%Users{}, users_params)</pre><pre>  case Repo.insert(changeset) do<br>    {:ok, _} -&gt;<br>      user = Repo.get_by(Users, username: username)<br>      new_conn = Guardian.Plug.api_sign_in(conn, user, :access)<br>      jwt = Guardian.Plug.current_token(new_conn)</pre><pre>      new_conn<br>      |&gt; put_status(:created)<br>  end<br>end</pre><p>Now, we are not only inserting a new row into our database but authenticating the user via Guardian.Plug.api_sign_in(conn, user, :access) as well as storing the JSON web token (just like we did when handling a login).</p><p>The final step on the server-side is to send a JSON object containing data for the current user and the JSON web token. We do this by adding a session view in <em>web/views/sessions_view.ex</em>.</p><p>In this file, we will return a JSON object containing two objects within it called <em>data</em> and <em>meta</em>.</p><pre>defmodule PhoenixUserAuthentication.SessionsView do<br>  use PhoenixUserAuthentication.Web, :view</pre><pre>  def render(&quot;show.json&quot;, %{user: user, jwt: jwt}) do<br>    %{<br>      data: user_data_json(user),<br>      meta: meta_json(jwt)<br>    }<br>  end</pre><pre>  def user_data_json(user) do<br>    %{<br>      id: user.id,<br>      username: user.username<br>    }<br>  end</pre><pre>  def meta_json(jwt) do<br>    %{<br>      token: jwt<br>    }<br>  end</pre><pre>end</pre><p><em>data</em> contains the id and username for the user and <em>meta </em>contains the token.</p><p>Let’s invoke the rendering of <em>show.json </em>within the <em>SessionsController</em> after a new connection:</p><pre>def create(conn, %{&quot;username&quot; =&gt; username, &quot;password&quot; =&gt; password}) do<br>  case authenticate(%{&quot;username&quot; =&gt; username, &quot;password&quot; =&gt; password}) do<br>    {:ok, user} -&gt;<br>      new_conn = Guardian.Plug.api_sign_in(conn, user, :access)<br>      jwt = Guardian.Plug.current_token(new_conn)</pre><pre>      new_conn<br>      |&gt; put_status(:created)<br>      |&gt; render(&quot;show.json&quot;, user: user, jwt: jwt) # new insertion <br>    :error -&gt;<br>      conn<br>      |&gt; put_status(:unauthorized)<br>  end<br>end</pre><p>We also want to do this for the login happening in <em>UsersController</em>:</p><pre>def create(conn, %{&quot;users&quot; =&gt; users_params}) do<br>  changeset = Users.changeset(%Users{}, users_params)<br>  case Repo.insert(changeset) do<br>    {:ok, user} -&gt;<br>      new_conn = Guardian.Plug.api_sign_in(conn, user, :access)<br>      jwt = Guardian.Plug.current_token(new_conn)</pre><pre>      new_conn<br>      |&gt; put_status(:created)<br>      |&gt; render(PhoenixUserAuthentication.SessionsView, &quot;show.json&quot;, user: user, jwt: jwt)<br>  end<br>end</pre><p>Instead of writing another view, we can just add PhoenixUserAuthentication.SessionsView before the invoking of <em>show.json</em> in <em>session_view.ex</em>.</p><p><em>I know! Authentication is a pain first time around but we are almost done!</em></p><p>Let’s try logging in and seeing if the user is authenticated by updating <em>web/static/js/containers/Login.js </em>to make an HTTP request on submission:</p><pre>handleSubmit (event) {<br>  event.preventDefault();<br>  axios({<br>    method: &#39;post&#39;,<br>    headers: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    },<br>    url: &#39;<a href="http://localhost:4000/api/sessions&#39;">http://localhost:4000/api/sessions&#39;</a>,<br>    data: {<br>        username: this.state.username,<br>        password: this.state.password<br>    }<br>  })<br>    .then((response) =&gt; {<br>      console.log(response);<br>    });<br>}</pre><p>Run brunch build and try logging in using the same username and password when creating a user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkwhvzunr7ye-mNO4l4f3A.png" /></figure><p>After you submit, check the response which we had logged in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnHtrLhv1b9YaYcyz8ghCA.png" /></figure><p>We can see that it has retrieved the user from the database and provided a token!</p><p>Now, you could use the response to let React know that the user is authenticated and redirect a user to a client-side route that requires authentication for access. This falls outside the scope of this chapter, but you can <a href="https://medium.com/the-many/adding-login-and-authentication-sections-to-your-react-or-react-native-app-7767fd251bd1">see this helpful guide</a>.</p><p>To wrap up, let’s also check to see if a user is being authenticated when signing up as should occur given the code in <em>users_controller.ex</em>.</p><p>To make sure it’s working, we can log the response from an HTTP request at signup in <em>web/static/js/containers/Signup.js</em>:</p><pre>handleSubmit (event) {<br>  event.preventDefault();<br>  axios({<br>    method: &#39;post&#39;,<br>    headers: {&quot;Content-Type&quot;: &quot;application/json&quot;},<br>    url: &#39;<a href="http://localhost:4000/api/users&#39;">http://localhost:4000/api/users&#39;</a>,<br>    data: {<br>      users: {<br>        username: this.state.username,<br>        password: this.state.password<br>      }<br>    }<br>  })<br>    .then((response) =&gt; {<br>      console.log(response);<br>    });<br>}</pre><p>Run brunch build go to <a href="http://localhost:4000/">http://localhost:4000/</a>, and sign up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkiUT-bJNwlOI5eN3WgvNw.png" /></figure><p>Check the console and we should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcSZRt4k-4GDziEQ5DQtvw.png" /></figure><p>Woot woot! The user was authenticated but was it created in our database?</p><p>You bet yah!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z3lqPW2TrnRjTtgqAEMutg.png" /></figure><h3>Final Code</h3><p><a href="https://github.com/michaelmang/full-stack-react-phoenix/tree/master/phoenix_user_authentication">Available on GitHub.</a></p><h3>Concluding Thoughts</h3><p>Authentication is quite the beast for only being a sliver of an application. However, it’s one of those things that you learn once and can reuse over and over.</p><p>We now know the heart of full-stack web development which includes interacting with a database to populate our UI and authenticate users.</p><p>There are only a few things left to cover in this book. In the next chapter, we will be looking into bi-directional communication using Phoenix’s built-in channels.</p><h3>Chapter 9</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-9-channels-245a24647e84">Chapter 9 is now available.</a></p><h3>Sign Up for Notifications</h3><p><a href="http://codingartist.io/full-stack-react-phoenix/">Get notified when each chapter is released.</a></p><p>Cheers,<br>Mike Mangialardi<br>Founder of Coding Artist</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb1ff48a5e51" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-8-user-authentication-fb1ff48a5e51">Full-Stack React With Phoenix (Chapter 8 | User Authentication)</a> was originally published in <a href="https://medium.com/coding-artist">Coding Artist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack React With Phoenix (Chapter 7 | CRUD Operations)]]></title>
            <link>https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-7-crud-operations-79d4e5af9a0d?source=rss----6df8bca0c0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/79d4e5af9a0d</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Michael Mangialardi]]></dc:creator>
            <pubDate>Tue, 01 Aug 2017 02:19:29 GMT</pubDate>
            <atom:updated>2017-08-03T04:41:54.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TwFVlU8pHQEE-D1XC7f0Gw.png" /></figure><h3>Table of Contents</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Chapter 1 | Why Bother?</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Chapter 2 | Learning the Basics of Elixir</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4">Chapter 3 | Introduction to Phoenix</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-4-implementing-react-716979133669">Chapter 4 | Implementing React</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-5-working-with-postgresql-83ec4f3286b2">Chapter 5 | Working With PostgreSQL</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-6-creating-a-postgresql-api-service-9f2775161d3f">Chapter 6 | Creating a PostgreSQL API Service</a></p><h3>Scope of This Chapter</h3><p>In the previous chapter, we were able to start the process of programmatically creating a PostgreSQL API service.</p><p>So far, we have things working so a GET request on <em>/users </em>returns a JSON object containing all the rows in our <em>blogs </em>table in our database. Our React frontend is making the GET request and is rendering a blog card using the data in each row:</p><p>This chapter will be a continuation of this. We will finish off our API service so we can do <em>create</em>, <em>read, update</em>, and <em>delete</em> operations on our database and update the UI accordingly.</p><h3>Show and Create</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8Ehao6kxy9fGVvB_hoD2g.png" /></figure><p>In the previous chapter, we set up the following routes. We fully implemented the <em>get all blogs </em>interaction. However, we need to finish off the <em>getting a blog by id </em>(read) and <em>create a blog entry </em>(crate) interactions.</p><p>In <em>web/router.ex </em>in our <em>phoenix_react_curated_list </em>project, you will see the definition of these routes:</p><pre>scope &quot;/&quot;, PhoenixReactCuratedList do<br>  pipe_through :browser # Use the default browser stack</pre><pre>  get &quot;/&quot;, PageController, :index<br>  get &quot;/blogs&quot;, BlogsController, :index<br>  post &quot;/blogs&quot;, BlogsController, :create<br>  get &quot;/blogs/:id&quot;, BlogsController, :show<br>end</pre><p>The following line will call a function called <em>show </em>in <em>BlogsController </em>when there is a GET request on the <em>/blogs/:id </em>route:</p><pre>get &quot;/blogs/:id&quot;, BlogsController, :show</pre><p>This line will call a function called <em>create </em>in <em>BlogsController </em>when there is a POST request on the <em>/blogs </em>route:</p><pre>post &quot;/blogs&quot;, BlogsController, :create</pre><p>If we head over to <em>/web/controllers/blogs_controller.ex</em>, we can see that we’ve already added the shell of these functions:</p><pre>def create(conn, %{&quot;blogs&quot; =&gt; blogs_params}) do</pre><pre>end</pre><pre>def show(conn, %{&quot;id&quot; =&gt; id}) do</pre><pre>end</pre><h4>Show</h4><p>Let’s start by implementing the <em>show </em>function.</p><p>First, let’s add a line that uses Repo.get to query the <em>Blogs </em>table using the <em>id </em>parameter and return a blog:</p><pre>def show(conn, %{&quot;id&quot; =&gt; id}) do<br>  blog = Repo.get(Blogs, id)<br>end</pre><p>We also want to invoke our view to render a JSON object called <em>show.json </em>on our connection using the blog we stored:</p><pre>def show(conn, %{&quot;id&quot; =&gt; id}) do<br>  blog = Repo.get(Blogs, id)<br>  render conn, &quot;show.json&quot;, blog: blog<br>end</pre><p>Just like our index function, we will handle this render function in our view found in <em>web/views/blogs_view.ex.</em></p><p>We already have a render function that enumerates through a collection of all our blog posts and calls blogs_json on each iteration to return an object for each blog post within an array called <em>blogs</em>:</p><pre>{<br>    &quot;blogs&quot;: [<br>        {<br>            &quot;title&quot;: &quot;Full-Stack React With Phoenix...&quot;,<br>            &quot;subtitle&quot;: &quot;Benefits of an Elixir Backend&quot;,<br>            &quot;link&quot;: &quot;<a href="http://bit.ly/2w5aen8">http://bit.ly/2w5aen8</a>&quot;,<br>            &quot;image&quot;: &quot;<a href="http://bit.ly/2tOjzTM">http://bit.ly/2tOjzTM</a>&quot;,<br>            &quot;author&quot;: &quot;Mike Mangialardi&quot;<br>        }<br>    ]<br>}</pre><p>In this render function, we use the <em>blogs </em>parameter:</p><pre>%{blogs: blogs}</pre><p>To render a single JSON object for a single blog, we can write another render function and using %{blog: blog} as the parameter:</p><pre>def render(&quot;index.json&quot;, %{blog: blog}) do<br><br>end</pre><p>We want to return just one JSON object by passing this parameter to the blogs_json function like so:</p><pre># show single blog<br>def render(&quot;show.json&quot;, %{blog: blog}) do<br>  %{<br>    blog: blogs_json(blog)<br>  }<br>end</pre><p>Notice that I’ve added a comment to distinguish between the render functions.</p><p>Open up Postman test out a GET request on <a href="http://localhost:4000/blogs/1:"><em>http://localhost:4000/blogs/1</em></a><em> </em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TvRk8CyRAXZEHlUj3goZNQ.png" /></figure><p>Awesome!</p><p>We can see that we’ve successfully returned a single JSON object called <em>blog </em>where there is an id of 1 in our <em>blogs </em>table of our PostgreSQL database.</p><p>We won’t use this HTTP request in our React frontend but the process would be similar as our GET http://localhost:4000/blogs that we requested using axios:</p><pre>axios.get(&#39;<a href="http://localhost:4000/blogs&#39;">http://localhost:4000/blog/1&#39;</a>)<br>  .then(response =&gt; {<br>    this.setState({ blogs: response.data.blog });<br>  })<br>  .catch(error =&gt; {<br>    console.log(error);<br>  });</pre><p>The code above shows a GET request on <a href="http://localhost:4000/blogs&#39;">http://localhost:4000/blog/1</a> and the returned <em>blog </em>object being stored in the local state.</p><p>The data in the local state could then be used for rendering something to the UI.</p><h4>Create</h4><p>Now that we’ve finished the interaction to get a blog post by ID, let’s add the interaction to create a blog post via a POST request on <em>/blogs</em>.</p><p>The way this will work is that parameters will be provided on the HTTP request from our React frontend. The parameters will be used to insert a new row in our <em>blogs </em>table.</p><p>In order to work with parameters, we have to make an update to our model found in <em>web/models/blogs.ex</em>.</p><p>We need to add a <em>changeset</em> function:</p><pre>defmodule PhoenixReactCuratedList.Blogs do<br>  use PhoenixReactCuratedList.Web, :model<br>  schema &quot;blogs&quot; do<br>    field :title, :string<br>    field :subtitle, :string<br>    field :image, :string<br>    field :link, :string<br>    field :author, :string<br>    timestamps()<br>  end</pre><pre>  def changeset(struct, params \\ %{}) do<br>    struct<br>    |&gt; cast(params, [:title, :subtitle, :image, :link, :author])<br>  end</pre><pre>end</pre><p>According to <a href="https://hexdocs.pm/ecto/Ecto.Changeset.html">official documentation</a>, changesets allow filtering, casting, validation and definition of constraints when manipulating structs.</p><p>In our case, the changeset function will take in an empty <a href="https://elixir-lang.org/getting-started/structs.html">struct</a> and the parameters. It then <em>casts </em>the parameters as data for the empty struct with the approriate types as specified in our schema.</p><p>Back in our controller (<em>web/controllers/blogs_controller.ex</em>), we can call the changeset in our <em>create </em>function passing in any empty struct and the parameters:</p><pre>def create(conn, %{&quot;blogs&quot; =&gt; blogs_params}) do<br>  changeset = Blogs.changeset(%Blogs{}, blogs_params)<br>  <br>end</pre><p>We then use <em>changeset </em>to insert a row using Repo.insert and do something accordingly. In our case, we will render all the blogs<em> </em>in case of a successful insertion:</p><pre>def create(conn, %{&quot;blogs&quot; =&gt; blogs_params}) do<br>  changeset = Blogs.changeset(%Blogs{}, blogs_params)</pre><pre>  case Repo.insert(changeset) do<br>    {:ok, _blogs} -&gt;<br>      blogs = Repo.all(Blogs)<br>      render conn, &quot;index.json&quot;, blogs: blogs<br>  end<br>end</pre><p>Because we aren’t returning a JSON object like we did for our read operations, we are done on the server-side.</p><p>On the client-side, we need our React application to make this POST request with the parameters provided.</p><p>We can gather values to be used as parameters by making a form in React.</p><p>Currently, the top level of our React frontend is rendering the &lt;Blogs /&gt; component which ultimately causes all of our blog post cards to render:</p><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;Blogs /&gt;<br>    )<br>  }<br>}</pre><p>Let’s implement React Router so that we can render a component called <em>Form</em> on the /create route:</p><pre>npm install --save react-router-dom</pre><p>Then, let’s import it in our <em>web/static/js/app.js </em>file along with the Form component which we will make in just a bit:</p><pre>import { BrowserRouter as Router, Route, Link } from &#39;react-router-dom&#39;;<br>import Form from &#39;./containers/Form&#39;;</pre><p>In the <em>render </em>function, we can add our routes and the components to be rendered on them:</p><pre>render() {<br>  return (<br>    &lt;Router&gt;<br>      &lt;div&gt;<br>        &lt;Route exact path=&quot;/&quot; component={Blogs}/&gt;<br>        &lt;Route path=&quot;/create&quot; component={Form}/&gt;<br>      &lt;/div&gt;<br>    &lt;/Router&gt;<br>  )<br>}</pre><p>Under the <em>containers </em>folder, let’s create a file called <em>Form.js </em>which will contain the <em>Form </em>component which we previously imported.</p><p>First, let’s add the shell of the code:</p><pre>import React from &quot;react&quot;;<br>import axios from &quot;axios&quot;;</pre><pre>class Form extends React.Component {<br>  constructor() {<br>    super();<br>  }</pre><pre>  render() {<br>    return (<br>  <br>    )<br>  }<br>}</pre><pre>export default Form</pre><p>Above render(), let’s add a event handling function for a submitted form:</p><pre>handleSubmit (event) {<br>    <br>}</pre><p>Next, we can add the shell of a form that calls this event handler on the submission of the form:</p><pre>render() {<br>  return (<br>    &lt;form onSumbit={this.handleSumbit.bind(this)}&gt;<br><br>    &lt;/form&gt;<br>  )<br>}</pre><p>Within our form, we can use <a href="http://bulma.io/documentation/form/general/">predefined code via Bulma.io for our fields</a>:</p><pre>&lt;form onSumbit={this.handleSumbit.bind(this)}&gt;<br>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Title&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input className=&quot;input&quot; type=&quot;text&quot;/&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Subtitle&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input className=&quot;input&quot; type=&quot;text&quot;/&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Image&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input <br>        className=&quot;input&quot; <br>        type=&quot;text&quot; <br>        placeholder=&quot;Enter Image URL&quot;<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Link&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input className=&quot;input&quot; type=&quot;text&quot;/&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Author&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input className=&quot;input&quot; type=&quot;text&quot;/&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/form&gt;</pre><p>Before we write the code to handle our form, let’s make sure that we can navigate to this <em>Form </em>component via a button (predefined by Bulma) in our home/default component (<em>containers/Blogs.js</em>):</p><pre>import { Link } from &#39;react-router-dom&#39;;</pre><pre>//class Blogs extends React.Component</pre><pre>  //...</pre><pre>render() {<br>  const posts = this.state.blogs.map((blog, index) =&gt;<br>    &lt;BlogCard<br>      key = { index }<br>      title = { blog.title }<br>      subtitle = { blog.subtitle }<br>      image = { blog.image }<br>      link = { blog.link }<br>      author = { blog.author }<br>    /&gt;<br>  );<br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&quot;is-primary is-large&quot;<br>        style = {{<br>          position: &quot;absolute&quot;,<br>          top: &quot;10px&quot;,<br>          right: &quot;10px&quot;,<br>          padding: &quot;10px 15px&quot;,<br>          background: &quot;#00D1B2&quot;,<br>          color: &quot;#FFFFFF&quot;<br>        }}<br>      &gt;<br>        &lt;Link <br>          to=&quot;/create&quot; <br>          style = {{ color: &quot;white&quot; }}<br>        &gt;<br>        Create Blog Post<br>        &lt;/Link&gt;<br>      &lt;/div&gt;<br>    {posts}<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Run brunch build and go to the local host:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*bIz4QCa-cdDjKQrlKccypA.gif" /></figure><p>We can now see our button which links to our form.</p><p>Let’s finish this up by having our form collect the field values and use them as parameters in a POST request.</p><p>To do this, let’s begin by adding a local state to our <em>Form </em>component that will track all the values in our form:</p><pre>constructor() {<br>  super();<br>  this.state = {<br>    title: &#39;&#39;,<br>    subtitle: &#39;&#39;,<br>    image: &#39;&#39;,<br>    link: &#39;&#39;,<br>    author: &#39;&#39;<br>  };<br>}</pre><p>Next, we can bind the values from our inputs to our state like so:</p><pre>&lt;form onSumbit={this.handleSumbit.bind(this)}&gt;<br>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Title&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input<br>        className=&quot;input&quot;<br>        type=&quot;text&quot;<br>        value = {this.state.title}<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Subtitle&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input<br>        className=&quot;input&quot;<br>        type=&quot;text&quot;<br>        value = {this.state.subtitle}<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Image&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input<br>        className=&quot;input&quot;<br>        type=&quot;text&quot;<br>        placeholder=&quot;Enter Image URL&quot;<br>        value = {this.state.image}<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Link&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input<br>        className=&quot;input&quot;<br>        type=&quot;text&quot;<br>        value = {this.state.link}<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Author&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input<br>        className=&quot;input&quot;<br>        type=&quot;text&quot;<br>        value = {this.state.author}<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/form&gt;</pre><p>In the code above, we have added value = {this.state.___} in each input.</p><p>Next, we want to have the values update whenever there is a change within the fields. We can do this by having an event handler for each input:</p><pre>handleTitle(event) {<br>  this.setState({ title: event.target.value })<br>}</pre><pre>handleSubtitle(event) {<br>  this.setState({ subtitle: event.target.value })<br>}</pre><pre>handleImage(event) {<br>  this.setState({ image: event.target.value })<br>}</pre><pre>handleLink(event) {<br>  this.setState({ link: event.target.value })<br>}</pre><pre>handleAuthor(event) {<br>  this.setState({ author: event.target.value })<br>}</pre><p>These event handlers need to be called during an onChange event within each input:</p><pre>&lt;&lt;form onSubmit={this.handleSubmit.bind(this)}&gt;<br>  &lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Title&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input<br>        className=&quot;input&quot;<br>        type=&quot;text&quot;<br>        value = {this.state.title}<br>        onChange = {this.handleTitle.bind(this)}<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>&lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Subtitle&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input<br>        className=&quot;input&quot;<br>        type=&quot;text&quot;<br>        value = {this.state.subtitle}<br>        onChange = {this.handleSubtitle.bind(this)}<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>&lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Image&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input<br>        className=&quot;input&quot;<br>        type=&quot;text&quot;<br>        placeholder=&quot;Enter Image URL&quot;<br>        onChange = {this.handleImage.bind(this)}<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>&lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Link&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input<br>        className=&quot;input&quot;<br>        type=&quot;text&quot;<br>        value = {this.state.link}<br>        onChange = {this.handleLink.bind(this)}<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>&lt;div className=&quot;field&quot;&gt;<br>    &lt;label className=&quot;label&quot;&gt;Author&lt;/label&gt;<br>    &lt;div className=&quot;control&quot;&gt;<br>      &lt;input<br>        className=&quot;input&quot;<br>        type=&quot;text&quot;<br>        value = {this.state.author}<br>        onChange = {this.handleAuthor.bind(this)}<br>      /&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><pre>&lt;/form&gt;</pre><p>In the code above, we added onChange = {this.handle___.bind(this)} to every input.</p><p>Let’s test this form out by logging the local state in handleSubmit:</p><pre>handleSubmit (event) {<br>  event.preventDefault();<br>  console.log(this.state);<br>}</pre><p>We also need a button to submit this form:</p><pre>&lt;form onSumbit={this.handleSumbit.bind(this)}&gt;</pre><pre>//fields</pre><pre>  &lt;button<br>    type=&quot;submit&quot;<br>    value=&quot;Submit&quot;<br>    className=&quot;button is-primary&quot;<br>  &gt;<br>  Submit<br>  &lt;/button&gt;</pre><pre>&lt;/form&gt;</pre><p>Run brunch build and insert the following information in the form:</p><pre>Full-Stack React With Phoenix (Chapter 4 | Implementing React)<br>Phoenix Plus React<br><a href="http://bit.ly/2udts8Z">http://bit.ly/2udts8Z</a><br><a href="http://bit.ly/2vmhleA">http://bit.ly/2vmhleA</a><br>Mike Mangialardi</pre><p>Hit <strong>Submit </strong>and check the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-O3nfBBjcSBhk47GejJC-Q.png" /></figure><p>Sweet! All of the form values and being updated correctly.</p><p>Now, let’s update handleSubmit to make the POST request using these values as parameters:</p><pre>handleSubmit (event) {<br>  event.preventDefault();<br>  axios.post(&#39;<a href="http://localhost:4000/api/blogs&#39;">http://localhost:4000/api/blogs&#39;</a>, {<br>    headers: {&quot;Content-Type&quot;: &quot;application/json&quot;},<br>    data: {<br>      blogs: {<br>        title: this.state.title,<br>        subtitle: this.state.subtitle,<br>        image: this.state.image,<br>        link: this.state.link,<br>        author: this.state.author<br>      }<br>    }<br>  });<br>\</pre><p>There’s also a mistake which I recently caught which needs to be corrected.</p><p>In <em>web/router.ex</em>, we have all of our API routes passing through the browser pipeline and you’ll see there’s code commented out to have routes pass through an api pipeline:</p><pre>scope &quot;/&quot;, PhoenixReactCuratedList do<br>  pipe_through :browser # Use the default browser stack</pre><pre>  get &quot;/&quot;, PageController, :index<br>  get &quot;/blogs&quot;, BlogsController, :index<br>  post &quot;/blogs&quot;, BlogsController, :create<br>  get &quot;/blogs/:id&quot;, BlogsController, :show<br>end</pre><pre># Other scopes may use custom stacks.<br># scope &quot;/api&quot;, PhoenixReactCuratedList do<br>#   pipe_through :api<br># end</pre><p>For our GET requests, this hasn’t caused an issue. However, it will cause issue with our POST requests.</p><p>Let’s comment that block of code out and move our API routes there:</p><pre>scope &quot;/api&quot;, PhoenixReactCuratedList do<br>  pipe_through :api<br>  <br>  get &quot;/blogs&quot;, BlogsController, :index<br>  post &quot;/blogs&quot;, BlogsController, :create<br>  get &quot;/blogs/:id&quot;, BlogsController, :show<br>end</pre><p>Now, we can make the calls on the <em>/api/blogs </em>router.</p><p>Quickly, let’s update the two HTTP requests that we have in our React application.</p><p>In <em>web/static/js/containers/Blog.js</em>, update the following line:</p><pre>axios.get(&#39;<a href="http://localhost:4000/api/blogs&#39;">http://localhost:4000/api/blogs&#39;</a>)</pre><p>In <em>web/static.js/containers/Form.js</em>, update the following line:</p><pre>axios.post(&#39;<a href="http://localhost:4000/blogs&#39;">http://localhost:4000/api/blogs&#39;</a>, {</pre><p>Run brunch build and let’s try submitting the form again using the following information:</p><pre>Full-Stack React With Phoenix (Chapter 4 | Implementing React)<br>Phoenix Plus React<br><a href="http://bit.ly/2udts8Z">http://bit.ly/2udts8Z</a><br><a href="http://bit.ly/2vmhleA">http://bit.ly/2vmhleA</a><br>Mike Mangialardi</pre><p>Once you have submitted the form, open pgAdmin and view all the rows in out <em>blogs </em>table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDEzs06dOFMQ6oouaTGf2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbPKCvUenfLovZczm2g-yA.png" /></figure><p>Success! We have implemented dynamic blog post submissions using our Phoenix API and React.</p><p><strong>Note: </strong>I have an id of 7 for the second row because I did multiple tests in between.</p><p>If you go to <a href="http://localhost:4000/">http://localhost:4000/</a>, you will now see our second blog rendering to the UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-txs481Z0HtA4dag14xKEA.png" /></figure><p>Our show and create interactions are now complete!</p><h3>Delete</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gS05NBBUi4SkhIAvcwcSyw.png" /></figure><p><strong>Note: </strong>The routes have since been updated to <em>/api/blogs</em>.</p><p>Let’s move on to an example delete operation by implementing the interaction that will delete a blog post by id.</p><p>First, open <em>web/router.ex </em>and let’s add the route, request type, controller, and function to call:</p><pre>scope &quot;/api&quot;, PhoenixReactCuratedList do<br>  pipe_through :api</pre><pre>  get &quot;/blogs&quot;, BlogsController, :index<br>  post &quot;/blogs&quot;, BlogsController, :create<br>  get &quot;/blogs/:id&quot;, BlogsController, :show<br>  delete &quot;/blogs/:id&quot;, BlogsController, :delete<br>end</pre><p>Next, we can open <em>web/controllers/blogs_controller.ex </em>and write out our delete function:</p><pre>def delete(conn, %{&quot;id&quot; =&gt; id}) do<br>  blog = Repo.get(Blogs, id)<br>  Repo.delete(blog)<br>  blogs = Repo.all(Blogs)<br>  render conn, &quot;index.json&quot;, blogs: blogs<br>end</pre><p>delete is similar to show in that it takes an id parameter to get a row from our database. However, it has an additional step to delete the retrieved row.</p><p>Once this occurs, all of the current blog posts will render. We should see the specified blog post removed.</p><p>Let’s test out a delete using Postman.</p><p>Send a DELETE request on <a href="http://localhost:4000/api/blogs/1">http://localhost:4000/api/blogs/1</a><em>.</em></p><p>If we check pgAdmin, we can see our first row removed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMDG3YvHJZmTDHvEzbE3Qw.png" /></figure><h3>Update</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rzkj0Efwn-qG3K8LYqPIbA.png" /></figure><p><strong>Note: </strong>The routes have since been updated to <em>/api/blogs</em>.</p><p>The final interaction to implement will be updating a blog by id.</p><p>This will be very similar to our create interaction with a few modifications.</p><p>First, open <em>web/router.ex </em>and let’s add the route, request type, controller, and function to call:</p><pre>scope &quot;/api&quot;, PhoenixReactCuratedList do<br>  pipe_through :api</pre><pre>  get &quot;/blogs&quot;, BlogsController, :index<br>  post &quot;/blogs&quot;, BlogsController, :create<br>  get &quot;/blogs/:id&quot;, BlogsController, :show<br>  delete &quot;/blogs/:id&quot;, BlogsController, :delete<br>  put &quot;/blogs/:id&quot;, BlogsController, :update<br>end</pre><p>Next, we can open <em>web/controllers/blogs_controller.ex </em>and write out our update function:</p><pre>def update(conn, %{&quot;id&quot; =&gt; id, &quot;blogs&quot; =&gt; blogs_params}) do<br>  blog = Repo.get(Blogs, id)<br>  changeset = Blogs.changeset(blog, blogs_params)</pre><pre>  case Repo.update(changeset) do<br>    {:ok, _blog} -&gt;<br>      blog = Repo.get(Blog, id)<br>      render conn, &quot;show.json&quot;, blog: blog<br>  end<br>end</pre><p>In the code above, we use the id parameter to retrieve a blog post and then use it to create a changeset. Just like in our create interaction, we use that changeset for our operation and add some logic on how to handle a successful interaction. Instead of Repo.insert, however, we use Repo.update. On a successful interaction, a JSON object with the data for that blog post is rendered.</p><p>Open <em>web/static/js/app.js </em>and let’s add a client-side route for a form that will give us parameters for our update:</p><pre>&lt;Router&gt;<br>  &lt;div&gt;<br>    &lt;Route exact path=&quot;/&quot; component={Blogs}/&gt;<br>    &lt;Route path=&quot;/create&quot; component={Form}/&gt;<br>    &lt;Route path=&quot;/update&quot; component={UpdateForm}/&gt;<br>  &lt;/div&gt;<br>&lt;/Router&gt;</pre><p>We also import the <em>UpdateForm </em>component which we will create next:</p><pre>import UpdateForm from &#39;./containers/UpdateForm&#39;;</pre><p>Create a file called <em>UpdateForm.js </em>within the <em>containers </em>folder to match our import and add the shell of our code:</p><pre>import React from &quot;react&quot;;<br>import axios from &quot;axios&quot;;</pre><pre>class UpdateForm extends React.Component {<br>  render() {</pre><pre>  }<br>}</pre><pre>export default UpdateForm</pre><p>Within our class, we can paste all the contents of <em>Form.js</em>.</p><p>We then just need to tweak handleSubmit with the correct HTTP request method and the URL like so:</p><pre>handleSubmit (event) {<br>  event.preventDefault();<br>  axios({<br>    method: &#39;put&#39;,<br>    headers: {&quot;Content-Type&quot;: &quot;application/json&quot;},<br>    url: &#39;<a href="http://localhost:4000/api/blogs&#39;">http://localhost:4000/api/blogs/7&#39;</a>,<br>    data: {<br>      blogs: {<br>        title: this.state.title,<br>        subtitle: this.state.subtitle,<br>        image: this.state.image,<br>        link: this.state.link,<br>        author: this.state.author<br>      }<br>    }<br>  });<br>}</pre><p>Ideally, the id would be passed to this component via a <a href="https://reacttraining.com/react-router/web/example/url-params">React Router parameter</a> based on some input (i.e. clicking an edit icon on a blog card from the home page) and a variable would be appended to our URL like so:</p><pre>url: &#39;<a href="http://localhost:4000/api/blogs&#39;">http://localhost:4000/api/blogs/&#39;</a> + this.state.id,</pre><p>However, we just manually specified the URL to save time:</p><pre>url: &#39;<a href="http://localhost:4000/api/blogs&#39;">http://localhost:4000/api/blogs/7&#39;</a>,</pre><p><strong>Note: </strong>I currently have one row in my <em>blogs </em>table with an id of 7. Update for your table.</p><p>Let’s add a button to our home/main component as defined in <em>Blogs.js</em> that will link to this <em>UpdateForm</em> component:</p><pre>return (<br>  &lt;div&gt;<br>    &lt;div className=&quot;is-primary is-large&quot;<br>      style = {{<br>        position: &quot;absolute&quot;,<br>        top: &quot;10px&quot;,<br>        right: &quot;10px&quot;,<br>        padding: &quot;10px 15px&quot;,<br>        background: &quot;#00D1B2&quot;<br>      }}<br>    &gt;<br>      &lt;Link<br>        to=&quot;/create&quot;<br>        style = {{ color: &quot;white&quot; }}<br>      &gt;<br>      Create Blog Post<br>      &lt;/Link&gt;<br>    &lt;/div&gt;<br>    &lt;div className=&quot;is-primary is-large&quot;<br>      style = {{<br>        position: &quot;absolute&quot;,<br>        top: &quot;80px&quot;,<br>        right: &quot;10px&quot;,<br>        padding: &quot;10px 15px&quot;,<br>        background: &quot;#00D1B2&quot;<br>      }}<br>    &gt;<br>      &lt;Link<br>        to=&quot;/update&quot;<br>        style = {{ color: &quot;white&quot; }}<br>      &gt;<br>      Edit Blog Post<br>      &lt;/Link&gt;<br>    &lt;/div&gt;<br>  {posts}<br>  &lt;/div&gt;<br>)</pre><p>Run brunch build, click on <strong>Edit Blog Post</strong>, and fill out the form with new information.</p><p>You can update with any information that you want. In my case, the update made the following changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6HEiWFEKIKxESAv7sJyEQ.png" /></figure><p>Amazing! We have finished all of our CRUD operations for our API service!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*L8nLPhXvLMmYzGQ9WLxgqA.gif" /></figure><h3>Final Code</h3><p><a href="https://github.com/michaelmang/full-stack-react-phoenix/tree/master/final%20phoenix_react_curated_list/phoenix_react_curated_list">Available on GitHub.</a></p><h3>Concluding Thoughts</h3><p>That’s it! You now know the heart of server-side development which includes routing a single page React app on the frontend and creating an API service for the frontend to retrieve data.</p><p>There’s still one major use case for an API service that requires a bit more work and explanation, user authentication.</p><p>We will proceed to explain this major use case in the next chapter.</p><h3>Chapter 8</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-8-user-authentication-fb1ff48a5e51">Chapter 8 is now available.</a></p><h3>Sign Up for Notifications</h3><p><a href="http://codingartist.io/full-stack-react-phoenix/">Get notified when each chapter is released.</a></p><p>Cheers,<br>Mike Mangialardi<br>Founder of Coding Artist</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79d4e5af9a0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-7-crud-operations-79d4e5af9a0d">Full-Stack React With Phoenix (Chapter 7 | CRUD Operations)</a> was originally published in <a href="https://medium.com/coding-artist">Coding Artist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack React With Phoenix (Chapter 6 | Creating a PostgreSQL API Service)]]></title>
            <link>https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-6-creating-a-postgresql-api-service-9f2775161d3f?source=rss----6df8bca0c0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/9f2775161d3f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Michael Mangialardi]]></dc:creator>
            <pubDate>Sat, 29 Jul 2017 13:01:31 GMT</pubDate>
            <atom:updated>2018-08-13T17:14:58.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lePcaaRN74qQ7_DllLe6-Q.png" /></figure><h3>Table of Contents</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Chapter 1 | Why Bother?</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Chapter 2 | Learning the Basics of Elixir</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4">Chapter 3 | Introduction to Phoenix</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-4-implementing-react-716979133669">Chapter 4 | Implementing React</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-5-working-with-postgresql-83ec4f3286b2">Chapter 5 | Working With PostgreSQL</a></p><h3>Before We Begin</h3><p>Make sure to <a href="https://www.pgadmin.org/">install pgAdmin</a> if you have not already.</p><p>Also, <a href="https://www.getpostman.com/">install Postman</a> which will be used to test out our API service.</p><h3>Scope of This Chapter</h3><p>You can think of the previous chapter as a bootstrapped way to get a sneak preview of what we are doing in this chapter. In this chapter, we are going to be creating a PostgreSQL API service with Phoenix so that we can make HTTP requests from a React frontend to create, read, update, and delete from our database.</p><p>In the previous chapter, we got started with this using a built-in generator. For learning purposes, we are going to do this programmatically so we can really grasp what’s going on. This is probably the most important chapter in this book so pay attention and I’ll do my best to explain well.</p><h3>Getting Started</h3><p>We want to continue in the <em>phoenix_curated_list </em>project. The end goal is to have a curated list of blog posts rendering using data from PostgreSQL. However, we want to start with a clean slate and have all the generated files from the previous chapter removed.</p><p>The easiest way to do this will be to create a new project from scratch.</p><p>First, let’s create a new project called <em>phoenix_react_curated_list</em>:</p><pre>mix phoenix.new phoenix_react_curated_list</pre><pre>cd phoenix_react_curated_list</pre><p>Next, make sure to have your PostgreSQL server running.</p><p>If we go to <em>config/dev.exs</em>, we can check our configurations for PostgreSQL at the bottom:</p><pre># Configure your database<br>config :phoenix_react_curated_list, PhoenixReactCuratedList.Repo,<br>  adapter: Ecto.Adapters.Postgres,<br>  username: &quot;postgres&quot;,<br>  password: &quot;postgres&quot;,<br>  database: &quot;phoenix_react_curated_list_dev&quot;,<br>  hostname: &quot;localhost&quot;,<br>  pool_size: 10,<br>  port: 5432 # I added this, default is 5432</pre><p>As noted in the comments, I added the port: 5432 line because I like to manually specify the port. The default port is 5432 for the PostgreSQL server so the configuration file omits this line by default.</p><p>Recall, <a href="https://hexdocs.pm/ecto/">Ecto</a> is the Elixir tool used for reading and writing to different databases, modeling our domain data, and writing complex queries.</p><p>It’s composed of 4 different parts as noted in the official Phoenix documentation:</p><ul><li>Repo — A repository represents a connection to an individual database. Every database operation is done via the repository.</li><li>Model — Models are our data definitions. They define table names and fields as well as each field’s type. Models also define associations — the relationships between models.</li><li>Query — Queries tie both models and repositories together, allowing us to elegantly retrieve data from the repository and cast it into the models themselves.</li><li>Changeset — Changesets declare transformations we need to perform on our model data before our application can use it. These include type casting, validations, and more.</li></ul><p>When creating a project, Phoenix has also automatically configured a repo which is the connection to our database which we can use to make operations on our database. However, we don’t have any code for models, queries, or changesets.</p><p>Let’s go ahead and create the phoenix_react_curated_list_dev database specified in the configuration via Ecto by running:</p><pre>mix ecto.create</pre><p>Go ahead and open pgAdmin once this completes.</p><p><strong>Note for Mac users: </strong>I ran into issues with pgAdmin not opening after installation. Make sure to drag the application found under devices into your applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uk-rxyunlNXzCgOzCvPuUw.png" /></figure><p>Then, open pgAdmin from the applications folder.</p><p>With pgAdmin open, go to <strong>File </strong>— <strong>Create</strong> — <strong>Server</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QV4hld9e4hUFXPVBpazpHw.png" /></figure><p>Name the server <strong>Phoenix </strong>and match the following information in <strong>Connection</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*fILGcwkd06NUH8cBEo396Q.png" /></figure><p>Make sure to enter the password which is <em>postgres </em>by default as we have already mentioned.</p><p>We will now be able to manage all the databases on port 5432. This includes the <em>phoenix_react_curated_list_dev </em>database which we just recently created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*M1llInJZsQjyfp9wfwxL4A.png" /></figure><h3>Creating Our First Table Programmatically</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h107L8ZNduxETBCqG6b09g.png" /></figure><p>Back to our project, we need to start the process of programmatically doing what was done using phoenix.gen.html without exception to the views and templates to do CRUD operations through a webpage as we will omit that.</p><p>As we did in the previous chapter, we want to create a table called <em>Blogs</em><strong> </strong>with the following fields:</p><pre>Blogs <br>_____<br>    <br>    title | subtitle | image | link | author</pre><pre>1</pre><pre>2</pre><pre>3</pre><pre>...</pre><p>First, we will manually create the model which includes a schema defining the shape of our data and a changeset which we will unpack later.</p><p>Under <em>web/models</em>, create a new file called <em>blogs.ex</em>.</p><p>In this file, we can start by adding an outermost module and specify the use of a <em>model </em>module within it:</p><pre>defmodule PhoenixReactCuratedList.Blogs do<br>  use PhoenixReactCuratedList.Web, :model</pre><pre>end</pre><p>This <em>model </em>module is defined in <em>web/web.ex</em>:</p><pre>def model do<br>  quote do<br>    use Ecto.Schema</pre><pre>    import Ecto<br>    import Ecto.Changeset<br>    import Ecto.Query<br>  end<br>end</pre><p>You just need to know that it imports all the Ecto stuff we need to create our complete model.</p><p>Next, we add a schema function that specifies the name of our table, the fields, and the types of the fields:</p><pre>defmodule PhoenixReactCuratedList.Blogs do<br>  use PhoenixReactCuratedList.Web, :model</pre><pre>  schema &quot;blogs&quot; do<br>    field :title, :string<br>    field :subtitle, :string<br>    field :image, :string<br>    field :link, :string<br>    field :author, :string</pre><pre>    timestamps()<br>  end<br>  <br>end</pre><p>We also include timestamps via timestamps().</p><p>The necessity of this schema is that our project now knows how a table in our database is shaped so it can interact with it via the repo accordingly.</p><p>Save the model. We now need to create a table following the schema defined in this model. Again, we can do this via a <em>migration</em>.</p><p>I mentioned in the previous chapter that you can think of the word migration as expressing the action of moving a table into our database using the field definitions outlined in the schema within our model.</p><p>While we won’t be using the phoenix.gen.html generator which generated a ton of extra stuff for us, we can generate the boilerplate of a migration file.</p><p>The migration file will be used to create the <em>blogs </em>table in our database following the shape specified in our schema.</p><p>To generate the boilerplate migration file, we can run:</p><pre>mix ecto.gen.migration blogs</pre><p>The syntax for the code above is as follows:</p><pre>mix ecto.gen.migration *table specified in schema*</pre><p>Now, open up this file found under <em>priv/repo/migrations</em>:</p><pre>defmodule PhoenixReactCuratedList.Repo.Migrations.Blogs do<br>  use Ecto.Migration</pre><pre>  def change do</pre><pre>  end<br>end</pre><p>Within the change function, we need to write the code that will migrate our table to the database when executed.</p><p>First, we can add a create table function within the <em>change </em>function:</p><pre>defmodule PhoenixReactCuratedList.Repo.Migrations.Blogs do<br>  use Ecto.Migration</pre><pre>  def change do<br>    create table(:blogs) do</pre><pre>    end<br>  end</pre><pre>end</pre><p>We can then simply paste in the contents of our schema function found in <em>web/models/blogs.ex</em> and prepend add:</p><pre>defmodule PhoenixReactCuratedList.Repo.Migrations.Blogs do<br>  use Ecto.Migration</pre><pre>  def change do<br>    create table(:blogs) do<br>      add :title, :string<br>      add :subtitle, :string<br>      add :image, :string<br>      add :link, :string<br>      add :author, :string</pre><pre>    timestamps()<br>    end<br>  end<br>end</pre><p>We are now ready to execute our migration by running the following:</p><pre>mix ecto.migrate</pre><p>Let’s see if it worked!</p><p>Refresh our Phoenix server in pgAdmin:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*q_sHbkKSVSerfPxPhU16lw.png" /></figure><p>Expand our schema under <em>Databases/phoenix_react_curtated_list_dev/schemas/public:</em></p><p>Underneath <strong>tables</strong>, we can see that the <em>blogs </em>table and the table with meta data of our migrations were both added!</p><p>If you expand the <strong>blogs</strong> table, you will see our columns (fields) match exactly like we had specified in our schema including the added timestamp information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*BNoggfP0AXTYWhOtOucoKA.png" /></figure><p>Sweet! Give yourself a pat on the back.</p><h3>Updating the Router &amp; Adding Our Controller</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A18x_NuGFcxOsO6jASFbDQ.png" /></figure><p>Now that we have a table, we need to create the API service so we can do CRUD operations via HTTP requests from our frontend.</p><h4>Router</h4><p>In our router, we define the routes for our API service. Each route can be used for different types of interactions depending on the type of HTTP request. If you are unfamiliar with HTTP request, <a href="https://www.tutorialspoint.com/http/http_requests.htm">check out this handy resource</a>.</p><p>For our API service, we need to have HTTP requests that will ultimately execute CRUD operations on our database.</p><p>Here’s a table showing the different routes, the HTTP requests, and the interactions that we want as a result for just our create and read operations (we will finish off the rest of the CRUD operations later):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8Ehao6kxy9fGVvB_hoD2g.png" /></figure><p>Open <em>web/router.ex </em>so we can add these routes.</p><p>We need to specify the HTTP verbage, the routes, the controller, and the function to call in the controller. The functions in our controller will be invoking the interactions with our database to perform our operations.</p><p>Here’s what our routes should look like to match the table shown above:</p><pre>scope &quot;/&quot;, PhoenixReactCuratedList do<br>  pipe_through :browser # Use the default browser stack</pre><pre>  get &quot;/&quot;, PageController, :index<br>  get &quot;/blogs&quot;, BlogsController, :index # show all blog posts<br>  post &quot;/blogs&quot;, BlogsController, :create # create blog post entry<br>  get &quot;/blogs/:id&quot;, BlogsController, :show # show a single blog post<br>end</pre><p><strong>Note:</strong> In the previous chapter (when we just generated everything really quickly), we used resources “/blogs&quot;, BlogsController. resources is a shorthand for manually writing out all the common types of HTTP requests paths and parameters for us. I’m purposely avoiding this so we can really understand how everything works.</p><h4>Controller</h4><p>We are now ready to write the <em>BlogsController </em>which we have specified in our routes.</p><p>Add a file called <em>blogs_controller.ex </em>under <em>web/controllers</em>.</p><p>In this file, we can add the shell of our code:</p><pre>defmodule PhoenixReactCuratedList.BlogsController do<br>  use PhoenixReactCuratedList.Web, :controller</pre><pre>  def index(conn, _params) do</pre><pre>  end</pre><pre>  def create(conn, _params) do</pre><pre>  end</pre><pre>  def show(conn, _params) do</pre><pre>  end</pre><pre>end</pre><p>In the code above, we have added the functions which we specified in our router.</p><p>Next, we can update _params where parameters are used:</p><pre>def create(conn, %{&quot;blogs&quot; =&gt; blogs_params}) do</pre><pre>end</pre><pre>def show(conn, %{&quot;id&quot; =&gt; id}) do</pre><pre>end</pre><p>A POST request on /blogs will contain URL parameters that will be used to <em>create</em> a new row in our <em>Blogs </em>table. Therefore, we will just have our parameters stored as <em>blog_params. </em>Recall, parameters are specified in <a href="https://elixirschool.com/en/lessons/basics/collections/#maps">maps</a>.</p><p>A GET request on /blogs/:id will <em>show</em> a blog post. We store the id parameter that will be included in the path into a map.</p><p>The create and show functions will require a bit more logic. Let’s just finish writing out the index<em> </em>function to show all our blogs in the database.</p><p>We have mentioned several times now that our repo is used to connect to our database and provides the means to interact with it. There are <a href="https://hexdocs.pm/ecto/Ecto.Repo.html#callbacks">several callbacks</a> that can be used to perform operations via our repo.</p><p>To fetch all entries we can use, Repo.all().</p><p>Therefore, let’s add the following:</p><pre>def index(conn, _params) do<br>  blogs = Repo.all()<br>end</pre><p>We are going to store the fetching of all entries in our <em>Blogs </em>table in a new variable called <em>blogs</em>.</p><p>The Repo.all() callback just needs to know which table to fetch information from and how the table is defined. This, as we know, is specified in our model which is accessible at PhoenixReactCuratedList.Blogs.</p><p>Writing out PhoenixReactCuratedList.Blogs is a bit tedious, therefore, we can create an alias so we can just write Blogs<em> </em>which will be equivalent to writing out PhoenixReactCuratedList.Blogs:</p><pre>defmodule PhoenixReactCuratedList.BlogsController do<br>  use PhoenixReactCuratedList.Web, :controller</pre><pre>  alias PhoenixReactCuratedList.Blogs #insert this line<br>  <br>  # ....</pre><p>Now, we can finish off our <em>index</em> function:</p><pre>def index(conn, _params) do<br>  blogs = Repo.all(Blogs)<br>end</pre><p>The code above will fetch all of our blogs within the <em>Blogs </em>table.</p><p>The final step to return blogs as a JSON object when our frontend makes the HTTP request. We will do that next.</p><h3>Returning a JSON Object Via a View</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QF7T-DBlBS9NXqqII_oOdw.png" /></figure><p>Before creating our view, we need to specify the name of JSON object that we want to return and pass the blogs stored in blogs. Therefore, we can add:</p><pre>def index(conn, _params) do<br>  blogs = Repo.all(Blogs)<br>  render conn, &quot;index.json&quot;, blogs: blogs<br>end</pre><p>Now, let’s create a view called <em>blogs_view.ex </em>under <em>web/views</em>.</p><p>We can start by adding a typical view like we did in our introduction to Phoenix:</p><pre>defmodule PhoenixReactCuratedList.BlogsView do<br>  use PhoenixReactCuratedList.Web, :view<br>end</pre><p>Now, let’s manually add a render function that will enumerate through our blogs and call another function called blogs_json which creates the JSON object:</p><pre>def render(&quot;index.json&quot;, %{blogs: blogs}) do<br>  %{<br>      blogs: Enum.map(blogs, &amp;blogs_json/1)<br>   }<br>end</pre><pre>def blogs_json(blog) do<br>  %{<br>     title: blog.title,<br>     subtitle: blog.subtitle,<br>     image: blog.image,<br>     link: blog.link,<br>     author: blog.author<br>  }<br>end</pre><p>In the code above, render enumerates through the blogs map which contains all the fetched rows in our <em>Blogs </em>table. &amp;blogs_json/1 is shorthand for calling blog_json and passing in blog row on the current iteration. /1 is required at the end to specify the blogs_json function call will just have one parameter passed in.</p><p>blogs_json(blog) takes in the blog post and uses its information to create a map that is the Elixir equivalent of a JSOB object.</p><p>The render function ultimately returns <em>blogs </em>which will contain the map for each blog post. Because we passed in index.json, the HTTP request will return a JSON object containing an array called <em>blogs </em>with an individual object for all of our blog posts.</p><p>Let’s manually add a row in our Blogs table and test out this API.</p><p>Open pgAdmin and refresh our Phoenix server.</p><p>Then, expand our <em>blogs </em>table and then expand <em>columns</em>.</p><p>We need to make two quick edits before we manually enter in a row.</p><p>We need our timestamp columns (<em>inserted_at</em> and <em>updated_at</em>) to be populated automatically using the following sql expression: now()</p><p>Right-click <strong>inserted_at </strong>and click <strong>properties</strong>.</p><p>Select the <strong>definition </strong>tab and add now() as the default value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*peEaoX6PMF9MGIZzC0Uikg.png" /></figure><p>Repeat this same process for <strong>updated_at</strong>.</p><p>Now, let’s enter in a row of data.</p><p>Right-click <strong>blogs</strong>, hover over <strong>View/Edit Data</strong>, and then click <strong>All Rows</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdKkv32IHVg7Zzy7TzZrPQ.png" /></figure><p>We are now able to go through and add values for each field in our row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlwnWSc-AM-JdxaqALpwkw.png" /></figure><p>Here’s the information to use to fill in:</p><pre>1<br>Full-Stack React With Phoenix (Chapter 1 | Why Bother?)<br>Benefits of an Elixir Backend<br><a href="http://bit.ly/2tOjzTM">http://bit.ly/2tOjzTM</a><br><a href="http://bit.ly/2w5aen8">http://bit.ly/2w5aen8</a><br>Mike Mangialardi</pre><p><strong>Note:</strong> Leave the timestamp field empty as they will be generated automatically.</p><p>Once it is all entered, save and then click the lightning bolt to execute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*QTIsua3Zz5tJigqpwEtcXA.png" /></figure><p>Cool beans! We are now ready to test out our API.</p><p>To do this, we first need to fire up our server:</p><pre>mix phoenix.server</pre><p>Then, open <a href="https://www.getpostman.com/">Postman</a> which you should have installed earlier. Make sure GET is selected, paste in the path to fetch our blogs, and click <strong>send</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1WieIepIRrWAKjo-B7nEA.png" /></figure><p>It worked! We have received a <em>blogs </em>array with a JSON object containing an object for each blog post (row in our database). In this case, we have our single object for the row we just entered.</p><p>Awesome! This is really exciting because this means we can now make an HTTP request from our React frontend and use this data that is returned to populate our UI.</p><p>We will try this out next.</p><h3>Populating Our UI With React</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGizF64nKKCeOGBiqWttnA.png" /></figure><p>We still have to finish off our API service to do all the other CRUD operations. However, we will do this in the next chapter. To finish off this chapter, let’s make the HTTP request that we tested our in Postman and write React code so that a UI card will be rendered with each row in our database.</p><p>We can start by following the same steps outlined in Chapter 4 to setup our React frontend.</p><p>First, we can install our main dependencies:</p><pre>npm install --save react react-dom babel-preset-react</pre><p>Next, we configure our <em>brunch-config.js </em>file to apply presets for Babel and React:</p><pre>plugins: {<br>  babel: {<br>    presets: [&quot;es2015&quot;, &quot;react&quot;],<br>    // Do not use ES6 compiler in vendor code<br>    ignore: [/web\/static\/vendor/]<br>  }<br>},</pre><p>In addition, we add a whitelist in under the <em>npm </em>options in this file so that it is clear that we are going to use <em>react</em> and <em>react-dom</em>:</p><pre>npm: {<br>  enabled: true,<br>  whitelist: [&quot;phoenix&quot;, &quot;phoenix_html&quot;, &quot;react&quot;, &quot;react-dom&quot;]<br>}</pre><p>We can then create the target for our app in the <em>index.html.eex </em>template (delete everything else):</p><pre>&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;</pre><p>The app template contains a pre-populated header which we can remove:</p><pre>&lt;header class=&quot;header&quot;&gt;<br>  &lt;nav role=&quot;navigation&quot;&gt;<br>    &lt;ul class=&quot;nav nav-pills pull-right&quot;&gt;<br>      &lt;li&gt;&lt;a href=&quot;<a href="http://www.phoenixframework.org/docs">http://www.phoenixframework.org/docs</a>&quot;&gt;Get Started&lt;/a&gt;&lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/nav&gt;<br>  &lt;span class=&quot;logo&quot;&gt;&lt;/span&gt;<br>&lt;/header&gt;</pre><pre>^^^ delete this</pre><p>In web/static/js, let’s make a complete React project directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*nCvpiFjUESEVCW0MAlkY-A.png" /></figure><p>We just add <em>containers </em>and <em>presentationals </em>folders. <em>Containers </em>refer to active components where the API request will be made and the retrieved data will be passed down to a <em>presentational </em>component which presents something to our UI using the inherited props.</p><p>Open <em>app.js</em> and let’s add the following code:</p><pre>import &quot;phoenix_html&quot;<br>import React from &quot;react&quot;<br>import ReactDOM from &quot;react-dom&quot;<br>import Blogs from &quot;./containers/Blogs&quot;</pre><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;Blogs /&gt;<br>    )<br>  }<br>}</pre><pre>ReactDOM.render(<br>  &lt;App/&gt;,<br>  document.getElementById(&quot;app&quot;)<br>)</pre><p>In the code above, we define the top of our React hierarchy which will nest our container components called <em>Blogs</em>.</p><p>Let’s write <em>Blogs</em> in a new file called <em>Blogs.js</em> within the containers folder.</p><p>Let’s add the beginning of our code:</p><pre>import React from &quot;react&quot;</pre><pre>class Blogs extends React.Component {<br>  componentWillMount() {<br>    //add API request<br>  }</pre><pre>render() {<br>    //create a BlogCard component for each blog post in API request response<br>    return (<br>      &lt;div&gt;&lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default Blogs</pre><p>As the comments indicate, we need to add the API request and the code to render a <em>BlogCard</em> component for each blog post.</p><p>To make HTTP requests, we will use a library called <a href="https://github.com/mzabriskie/axios">axios</a>.</p><p>Let’s install that:</p><pre>npm install --save axios</pre><p>Then, let’s import it:</p><pre>import axios from &quot;axios&quot;</pre><p>Next, we can add the API request which will look like this:</p><pre>componentWillMount() {<br>  axios.get(&#39;<a href="http://localhost:4000/blogs&#39;">http://localhost:4000/blogs&#39;</a>)<br>    .then(function (response) {<br>      console.log(response);<br>    })<br>    .catch(function (error) {<br>      console.log(error);<br>    });<br>}</pre><p>This code can be read as: “Hey Axios! Can you get all the blog posts in our database doing a GET request on this path? After you do that, log the response for us so we can make sure it worked. If something goes wrong, just go ahead and log that too.”</p><p>Let’s compile our frontend code by running brunch build and then check the console in our local host:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Gk8x_bWutG2WsoYD7lI8A.png" /></figure><p>Woohoo! We can see our blogs array with the object for our single row in the database.</p><p>Now, we can store the <em>blogs </em>array from our response into a variable and use that to update a property in the local state (which we also will add):</p><pre>class Blogs extends React.Component {<br>  constructor() {<br>    super();<br>    this.state = { blogs: [] };<br>  }</pre><pre>  componentWillMount() {<br>    axios.get(&#39;<a href="http://localhost:4000/blogs&#39;">http://localhost:4000/blogs&#39;</a>)<br>      .then(response =&gt; {<br>        this.setState({ blogs: response.data.blogs });<br>      })<br>      .catch(error =&gt; {<br>        console.log(error);<br>      });<br>  }</pre><pre>  //...</pre><p>The next step is to iterate through each object in the <em>blogs </em>array and render a <em>BlogCard</em> component (which we haven’t created yet) for each blog post that passes down the information within the current object as props:</p><pre>render() {<br>  const posts = this.state.blogs.map((blog, index) =&gt;<br>    &lt;BlogCard<br>      key = { index }<br>      title = { blog.title }<br>      subtitle = { blog.subtitle }<br>      image = { blog.image }<br>      link = { blog.link }<br>      author = { blog.author }<br>    /&gt;<br>  )<br>  return (<br>    &lt;div&gt;<br>    {posts}<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Notice that we inject all of the <em>BlogCard </em>components stored in <em>posts </em>by doing {posts}.</p><p>Let’s import the <em>BlogCard</em> component which we will create next:</p><pre>import BlogCard from &quot;../presentationals/BlogCard&quot;</pre><p>Now, create a new file under the <em>presentationals </em>folder called <em>BlogCard.js</em>.</p><p>For writing the code that will render a blog card to the UI, we are going to use a CSS framework called <a href="http://bulma.io/">Bulma</a>. It comes with a predefined component which will be perfect for this.</p><p>We can use a CDN to easily add Bulma as a stylesheet in the head of <em>web/templates/app.html.eex</em>:</p><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;<a href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.4/css/bulma.css">https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.4/css/bulma.css</a>&quot;&gt;</pre><p>Back in <em>BlogCard.js</em>, let’s add the shell of our code and a <a href="http://bulma.io/documentation/components/card/">predefined blog card component</a> from Bulma with updates to change class to className so that it works with React:</p><pre>import React from &quot;react&quot;</pre><pre>class BlogCard extends React.Component {</pre><pre>render() {<br>    return (<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;div className=&quot;card-image&quot;&gt;<br>          &lt;figure className=&quot;image is-4by3&quot;&gt;<br>            &lt;img src=&quot;<a href="http://bulma.io/images/placeholders/1280x960.png">http://bulma.io/images/placeholders/1280x960.png</a>&quot; alt=&quot;Image&quot; /&gt;<br>          &lt;/figure&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;card-content&quot;&gt;<br>          &lt;div className=&quot;media&quot;&gt;<br>            &lt;div className=&quot;media-content&quot;&gt;<br>              &lt;p className=&quot;title is-4&quot;&gt;John Smith&lt;/p&gt;<br>              &lt;p className=&quot;subtitle is-6&quot;&gt;<a href="http://twitter.com/johnsmith">@johnsmith</a>&lt;/p&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default BlogCard</pre><p>Then, let’s update the information to inject the passed down props:</p><pre>render() {<br>  return (<br>    &lt;div className=&quot;card&quot;&gt;<br>      &lt;div className=&quot;card-image&quot;&gt;<br>        &lt;figure className=&quot;image is-4by3&quot;&gt;<br>          &lt;a href={this.props.link}&gt;<br>            &lt;img src={this.props.image} alt=&quot;Image&quot; /&gt;<br>          &lt;/a&gt;<br>        &lt;/figure&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;card-content&quot;&gt;<br>        &lt;div className=&quot;media&quot;&gt;<br>          &lt;div className=&quot;media-content&quot;&gt;<br>            &lt;p className=&quot;title is-4&quot;&gt;{this.props.title}&lt;/p&gt;<br>            &lt;p className=&quot;subtitle is-6&quot;&gt;{this.props.subtitle}&lt;/p&gt;<br>            &lt;p className=&quot;subtitle is-6&quot;&gt;By {this.props.author}&lt;/p&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>To finish off, delete all the code in <em>web/static/css/phoenix.css</em>. Then, add the following code in <em>app.css</em> which just adds a flexbox container to center our blog cards horizontally and vertically:</p><pre>#app {<br>  display: flex;<br>  align-items: center;<br>  justify-content: center;<br>  flex-direction: row;<br>  flex-wrap: wrap;<br>}</pre><p>Let’s run build brunch one more time and check the local host:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2jJ6JnUHRW_D-3UHR7diA.png" /></figure><p>Woohoo! We have successfully fetched our blogs using our Phoenix API server and rendered them with our React frontend!</p><h3>Final Code</h3><p><a href="https://github.com/michaelmang/full-stack-react-phoenix/tree/master/phoenix_react_curated_list">Available on GitHub.</a></p><h3>Concluding Thoughts</h3><p>I’m not sure about you, but I’m pretty pumped about our functioning API service. This is an incredibly useful skill to know. We still have to finish off the API service for the rest of our CRUD operations. However, let’s take a break at this point and do that in the next chapter.</p><h3>Chapter 7</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-7-crud-operations-79d4e5af9a0d">Chapter 7 is now available.</a></p><h3>Sign Up for Notifications</h3><p><a href="http://codingartist.io/full-stack-react-phoenix/">Get notified when each chapter is released.</a></p><p>Cheers,<br>Mike Mangialardi<br>Founder of Coding Artist</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f2775161d3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-6-creating-a-postgresql-api-service-9f2775161d3f">Full-Stack React With Phoenix (Chapter 6 | Creating a PostgreSQL API Service)</a> was originally published in <a href="https://medium.com/coding-artist">Coding Artist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack React With Phoenix (Chapter 5 | Working With PostgreSQL)]]></title>
            <link>https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-5-working-with-postgresql-83ec4f3286b2?source=rss----6df8bca0c0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/83ec4f3286b2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michael Mangialardi]]></dc:creator>
            <pubDate>Thu, 27 Jul 2017 06:11:18 GMT</pubDate>
            <atom:updated>2017-07-29T13:08:09.389Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5H14DQlS_s8L159JS1i6w.png" /></figure><h3>Table of Contents</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Chapter 1 | Why Bother?</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Chapter 2 | Learning the Basics of Elixir</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4">Chapter 3 | Introduction to Phoenix</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-4-implementing-react-716979133669">Chapter 4 | Implementing React</a></p><h3>Scope of This Chapter</h3><p>In order to really feel confident with a Phoenix and React stack, we want to create a project that is very close to a real-world scenario. In a real-world project, we would create an API service programmatically to interact with a database which would allow our React frontend to have dynamic data. We will be doing exactly that in the following chapters using a database called <a href="https://www.postgresql.org/">PostgreSQL</a>.</p><p>In this chapter, I want to lay the foundation for understanding what PostgreSQL is and do a bootstrapped example of creating data in our very own PostgreSQL database.</p><h3>SQL vs. NoSQL</h3><p>As you were learning React, you probably heard of two technologies for creating a database for your application, Firebase and MongoDB.</p><p>Both Firebase and MongoDB are known as <em>NoSQL</em> databases. Both of these databases store data as JSON objects internally. The data can also be shipped out via a request as a JSON object.</p><p>Here’s an internal look at a MongoDB database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*vO0yG5sbUUJBY7C2bOh4eA.png" /></figure><p>Because data is stored and shipped out as a JSON object, Firebase and MongoDB provide a lower learning curve for JavaScript developers. This also means that there is a great community and wealth of information behind each technology. For a lot of projects, these databases are great options.</p><p>However, NoSQL database (arguably) don’t provide the best way to store and query data. Reason being, the databases are not <em>relational</em>.</p><p>SQL (structured query language) databases are relational. Instead of storing data in JSON objects, they are stored in <em>tables</em>. A table consists of columns and rows. A row contains a single record and a column contains the values for certain attributes.</p><p>Let’s look at this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*ExR_CErzcbkfnZXIgOs7CA.png" /></figure><p>Again, we can see a record of information in each row and the values of certain attributes in the column.</p><p>So, how are SQL databases relational? Let’s look at another example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*hce14ckjd_pAV6VMNFgXDQ.png" /></figure><p>In the image above, we have a schema which shows the different tables in a database and the fields within them. There are also connected lines which show relations.</p><p>For example, in the students tables, there is a <em>primary key</em> called StudentID. A primary key is a field which uniquely identifies a record in a table. In other words, StudentID is the most appropriacfte (primary) unique identifier of the Students table. Now, StudentID might be needed to organize data in another table such as StudentTransactions. However, StudentID is not the best unique identified for student transactions even if it is needed in the table as a field. The use of a primary key in another table where it is needed but not primary makes it a <em>foreign key</em>. Looking at this example, we could say there is a <em>relation</em> between the Students table and the StudentTransactions table via the StudentID. By having these relations, it is easier to organize and query our tables.</p><p>In my opinion, I find SQL queries to be very readable and easy to follow. They have also been around for a long time and proven to be successful. For that reason, I will simply recommend that you look over this <a href="http://www.zentut.com/wp-content/uploads/downloads/2012/10/sqlcheatsheet2.pdf">SQL cheat sheet</a> to get a sense of how it works. I will still take the time to explain all the querying that we do in this book. For now, I just want you to understand the differences between SQL and NoSQL and the possible benefits.</p><h3>Introduction to PostgreSQL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4v6RuKEls7uby8oG0gIYRQ.png" /></figure><h4>Why PostgreSQL?</h4><p>In this book, we are going to be working with the SQL database technology called PostgreSQL.</p><p>PostgreSQL is configured as the default in Phoenix. It’s open-source and totally free. This is a strong reason as to why it has gathered and incredibly strong community and implemented some really powerful features. There are a ton of handy 3rd party, open-source tools available for it.PostgreSQL is very extendible, scales well, and a beast for complex design and data.</p><p>While NoSQL databases have their place for certain projects, I’m really excited to show you how to implement PostgreSQL in Phoenix.</p><h4>Getting Started</h4><p>When working with Node.js and MongoDB (as I have written about <a href="https://medium.com/coding-artist/redux-from-scratch-chapter-7-building-an-api-service-with-express-js-mongodb-3bde96e1f45b">here</a>), you can use a tool like Mongoose to be able to interact with a MongoDB database. Phoenix comes with a tool within the Elixir ecosystem called <a href="http://hexdocs.pm/ecto">Ecto</a> which allows for interaction with PostgreSQL, MySQL, SQLite 3m and MongoDB. In other words, it will allow us to talk to different kinds of databases so that we can do create, read, update, and delete operations (CRUD). Phoenix comes configured with PostgreSQL by default.</p><p>The <a href="http://www.phoenixframework.org/docs/overview">official Phoenix documentation</a> also provides some helpful definitions of Ecto terminology which we will be unpacking in more detail later on:</p><blockquote>Repo — A repository represents a connection to an individual database. Every database operation is done via the repository.</blockquote><blockquote>Model — Models are our data definitions. They define table names and fields as well as each field’s type. Models also define associations — the relationships between models.</blockquote><blockquote>Query — Queries tie both models and repositories together, allowing us to elegantly retrieve data from the repository and cast it into the models themselves.</blockquote><blockquote>Changeset — Changesets declare transformations we need to perform on our model data before our application can use it. These include type casting, validations, and more.</blockquote><p>Before we begin a new Phoenix project, you will need to install <a href="https://www.postgresql.org/download/">PostgreSQL</a>. If you are using a Mac, I highly recommend using <a href="https://postgresapp.com/">this installer</a>. It will allow you to install, configure, and fire up a PostgreSQL server with ease through a GUI.</p><p>For managing PostgreSQL databases through a GUI, I recommend <a href="https://www.pgadmin.org/">pgAdmin</a> or <a href="https://eggerapps.at/postico/">Postico</a>. In this book, we will use <a href="https://www.pgadmin.org/download/">pgAdmin</a> as it is cross-platform. Go ahead and download it.</p><p>However, for this chapter, we won’t need pgAdmin. Phoenix actually has a nice generator that will define a new table in our database and populate templates (as well as a view and controller as the means to achieve this) that will show us the contents of the table and allow us to do CRUD operations to it. We will switch up our approach in the next chapter and use pgAdmin.</p><p>Let’s go ahead and create a new project called <em>phoenix_curated_list</em>:</p><pre>mix phoenix.new phoenix_curated_list</pre><pre>cd phoenix_curated_list</pre><p>This project will just be used to render a curated list of blog posts using data from a PostgreSQL database.</p><p>Open the project in your code editor of choice.</p><p>If we go to <em>config/dev.exs</em>, we can see configurations for PostgreSQL at the bottom:</p><pre>config :phoenix_curated_list, PhoenixCuratedList.Repo,<br>  adapter: Ecto.Adapters.Postgres,<br>  username: &quot;postgres&quot;,<br>  password: &quot;postgres&quot;,<br>  database: &quot;phoenix_curated_list_dev&quot;,<br>  hostname: &quot;localhost&quot;,<br>  pool_size: 10</pre><p><strong>Note:</strong> <em>dev.exs</em> is configuration for a dev environment and <em>prod.exs</em> is configuration for production. Overall configuration happens in <em>config.exs</em>.</p><p>By default, PostgreSQL sets up a superuser with username and password of ‘postgres’<em>. </em>If you don’t have it configured this way, you can do so by running:</p><pre>psql postrgres</pre><pre>CREATE USER postgres;<br>ALTER USER postgres PASSWORD &#39;postgres&#39;;<br>ALTER USER postgres WITH SUPERUSER;</pre><p>By default, the port for PostgreSQL is 5432 and is not listed in the configuration. Personally, I’m using port 5431 so my configuration will look like this:</p><pre># Configure your database<br>config :phoenix_curated_list, PhoenixCuratedList.Repo,<br>  adapter: Ecto.Adapters.Postgres,<br>  username: &quot;postgres&quot;,<br>  password: &quot;postgres&quot;,<br>  database: &quot;phoenix_curated_list_dev&quot;,<br>  hostname: &quot;localhost&quot;,<br>  pool_size: 10,<br>  port: 5431</pre><p>In the code above, you will see PhoenixCuratedList.Repo. It was mentioned earlier that a <em>repo </em>is a connection with a database by which we can do operations/interactions with a database. Phoenix has already configured a repo by simply using an existing module called Ecto.Repo as can be seen in following code (<em>lib/phoenix_curated_list/repo.ex</em>):</p><pre>defmodule PhoenixCuratedList.Repo do<br>  use Ecto.Repo, otp_app: :phoenix_curated_list<br>end</pre><p>This repo was also included in the configuration found in <em>config/config.ex </em>and <em>config/dev.ex.</em></p><p>It’s important here to interject and explain that I’m just showing you this stuff about our repo so you know what it is and where it came. Again, it is simply a connection with our database by which we can do operations with our database. If you are interested in the nerdy details of it, you can check the <a href="https://hexdocs.pm/ecto/Ecto.Repo.html">Ecto.Repo documentation</a>.</p><p>We have our database and repo configuration settled by default, now let’s go ahead and create the database by running:</p><pre>mix ecto.create</pre><p>This will create a database called phoenix_curated_list_dev as we have specified in our configuration in <em>config/dev.ex</em>:</p><pre># Configure your database<br>config :phoenix_curated_list, PhoenixCuratedList.Repo,<br>  adapter: Ecto.Adapters.Postgres,<br>  username: &quot;postgres&quot;,<br>  password: &quot;postgres&quot;,<br>  database: &quot;<strong>phoenix_curated_list_dev</strong>&quot;,<br>  hostname: &quot;localhost&quot;,<br>  pool_size: 10,<br>  port: 5431</pre><p>If we fire up our Phoenix server using mix phoenix.server, we will see that the annoying error messages in the command line from earlier have ceased.</p><p>Ok. We have a database configured for our Phoenix project. Now what?</p><p>We need to create a model which can be defined as a data definition of a table, field (columns), and field types. This would be equivalent to defining a collection, its field, and field types in MongoDB.</p><p>Phoenix has a handy model generator that does the heavy lifting for us. It will create a model for us. With only a few additional actions, we can use the data definitions in our model to create a table in our database. The generator will also provide templates by which we can do create, read, update, and delete operations on a table.</p><p>First, let’s consider what table we ultimately want.</p><p>We want a table called <em>Blogs </em>with the following fields:</p><pre>Blogs Table<br>____________<br>    <br>    title | subtitle | image | link | author</pre><pre>1</pre><pre>2</pre><pre>3</pre><pre>...</pre><p>We also need to know the data types which can be expressed using atoms (note that the id will be generated automatically so it is omitted):</p><pre>title :string <br>subtitle :string <br>image :string <br>link :string <br>author :string</pre><p>Let’s use the generator phoenix.gen.html and specify that we want a table called <em>Blogs</em> which can be accessed on the <em>/blogs </em>path containing the fields shown above:</p><pre>mix phoenix.gen.html Blogs blogs title:string subtitle:string image:string link:string author:string</pre><p>As prompted in command line, we need to place the following code in our <em>router.ex </em>file:</p><pre>scope &quot;/&quot;, PhoenixCuratedList do<br>  pipe_through :browser # Use the default browser stack<br>  get &quot;/&quot;, PageController, :index<br>  resources &quot;/blogs&quot;, BlogsController<br>end</pre><p>This will allow us to see our table and do CRUD operations via the generated templates on the <em>/blogs </em>path.</p><p>If we open the generated model code in <em>web/models/blogs.ex</em>, we can see the following schema was generated defining the table, field, and field types:</p><pre>schema &quot;blogs&quot; do<br>  field :title, :string<br>  field :subtitle, :string<br>  field :image, :string<br>  field :link, :string<br>  field :author, :string</pre><pre>timestamps()<br>end</pre><p>For instructional purposes, here’s a snapshot via Postico of our current database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6-ycodeW32b4Awgd2IUVg.png" /></figure><p>Normally, tables in our database would appear here. However, there’s nothing.</p><p>This means we have to do an additional step to create our table. We need to create a table following the schema defined in our model.</p><p>In Phoenix, we do this via a <em>migration</em>. You can think of the word migration as expressing the action of moving a table into our database using the field definitions outlined in the schema within our model.</p><p>So, how do we do a migration?</p><p>As you may have guessed given the trend, Phoenix automatically generates a migration file which upon execution will create our table following our schema. The code that creates the table is found in this file located at <em>priv/repo/migrations/*timestamp*_create_blogs.exs</em>:</p><pre>def change do<br>    create table(:blogs) do<br>      add :title, :string<br>      add :subtitle, :string<br>      add :image, :string<br>      add :link, :string<br>      add :author, :string</pre><pre>      timestamps()<br>    end</pre><pre>end</pre><p>Recall, we mentioned that interactions with a database would happen through a repo. This is why the migrations are underneath the <em>repo </em>folder and the module definition containing the function shown above looks like this:</p><pre>defmodule PhoenixCuratedList.Repo.Migrations.CreateBlogs</pre><p>To run this, we can use the following command:</p><pre>mix ecto.migrate</pre><p>Via Postico, I’ll show you what our database looks like now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3Gh9JEgj2NPKY9PlvxV9A.png" /></figure><p>Two tables have been created. As expected, we have the <em>blogs </em>table and another table called <em>schema_migrations </em>which just logs meta data about our migrations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4svW8bGQrd1KrdMptcycg.png" /></figure><p>The <em>blogs </em>table looks just like we had specified:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezsPPY_XKRLBtLzo2311Pw.png" /></figure><p>Now, if you go to <a href="http://localhost:4000/blogs">http://localhost:4000/blogs</a>, you can see the template which shows us the <em>blogs </em>table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVjWTnLzJ2bn9o9nQxi_FQ.png" /></figure><p>We can click the “New blogs” link which brings us to another template with a form for adding a row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHLzJAsH51wKqU2fy7qgRA.png" /></figure><p>Insert a blog yourself and hit submit.</p><p>We are brought back to a complete view of our table with the new row added:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xp0KiC8hktMljm0YuEfUJg.png" /></figure><p>We can click the buttons on the right to show, edit, or delete this row.</p><p>For educational purposes, I’ll show this snapshot via Postico to confirm that a row truly was added in our table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQAHAGu-ZQ_j6UHv_49Byw.png" /></figure><p>Woot woot! We have created our first PostgreSQL database, created a table, and insert a row using Phoenix.</p><h3>Final Code</h3><p><a href="https://github.com/michaelmang/full-stack-react-phoenix/tree/master/phoenix_curated_list">Available on GitHub.</a></p><h3>Concluding Thoughts</h3><p>Using the Phoenix generator was bootstrapped way to create a model, execute a migration, and perform CRUD operations on the new table within our database. It’s not what we are going to use going forward which why I didn’t explain a lot of the files that were generated.</p><p>In a real-world scenario, we want to have an API service so we can do CRUD operations through HTTP requests from our React application. One of the generated files which I didn’t unpack actually did this, however, we are going to want to do this programmatically. This will allow us to not only be introduced to these new topics about PostgreSQL interactions with Phoenix (as we were in this chapter) but to retain them. While this means removing the use of the generator, and consequently the templates to view tables and do CRUD operations, we can do this via pgAdmin as I alluded to earlier.</p><p>Get ready. This next chapter will be the meat and potatoes of full-stack React development with Phoenix.</p><h3>Chapter 6</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-6-creating-a-postgresql-api-service-9f2775161d3f">Chapter 6 is now available.</a></p><h3>Sign Up for Notifications</h3><p><a href="http://codingartist.io/full-stack-react-phoenix/">Get notified when each chapter is released.</a></p><p>Cheers,<br>Mike Mangialardi<br>Founder of Coding Artist</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83ec4f3286b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-5-working-with-postgresql-83ec4f3286b2">Full-Stack React With Phoenix (Chapter 5 | Working With PostgreSQL)</a> was originally published in <a href="https://medium.com/coding-artist">Coding Artist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack React With Phoenix (Chapter 4 | Implementing React)]]></title>
            <link>https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-4-implementing-react-716979133669?source=rss----6df8bca0c0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/716979133669</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Michael Mangialardi]]></dc:creator>
            <pubDate>Wed, 26 Jul 2017 19:48:34 GMT</pubDate>
            <atom:updated>2017-08-05T14:38:19.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSc3bYxNXP4p6jingQZQwQ.png" /></figure><h3>Table of Contents</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Chapter 1 | Why Bother?</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Chapter 2 | Learning the Basics of Elixir</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4">Chapter 3 | Introduction to Phoenix</a></p><h3>Scope of This Chapter</h3><p>So far, I’ve been able to keep these chapters relatively short (<em>Well…I guess that depends on your perspective but I’m used to 8–20 hours of time to write my chapters</em>). You may be expecting this chapter to break that trend. However, a generated Phoenix application only needs a few tweaks in order to run a React frontend. In this chapter, we will render a very simple React frontend and you will know how to add setup a React frontend to any Phoenix project.</p><h3>Setting Up a React Frontend</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jmm6DM5ZusbG2dkmEywtA.png" /></figure><p>First things first, let’s create a new Phoenix project called <em>helloreact</em>:</p><pre>mix phoenix.new helloreact<br>cd hello-react</pre><p>Open up this project in a code editor and recall that there’s a <em>package.json </em>file in the root for our frontend configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Us4HWPlHbdLbtS2OELUVGw.png" /></figure><p>Therefore, we can go on ahead and install our React dependencies with npm:</p><pre>npm install --save react react-dom babel-preset-react</pre><p>Once this installs, we just need to apply Babel to preprocess our code which needs to happen in <em>brunch-config.js</em>. Recall, Brunch is an alternative to Webpack for asset managing. However, apply the Babel preset for React will be very similar:</p><pre>plugins: {<br>  babel: {<br>    presets: [&quot;es2015&quot;, &quot;react&quot;],<br>    // Do not use ES6 compiler in vendor code<br>    ignore: [/web\/static\/vendor/]<br>  }<br>},</pre><p>In addition, we need to add a whitelist in under the <em>npm </em>options in this file so that it is clear that we are going to use <em>react</em> and <em>react-dom</em>:</p><pre>npm: {<br>  enabled: true,<br>  whitelist: [&quot;phoenix&quot;, &quot;phoenix_html&quot;, &quot;react&quot;, &quot;react-dom&quot;]<br>}</pre><p>We could manually build our frontend using brunch build, however, this will run when we fire up our server.</p><p>For now, let’s go ahead and add a very simple React app.</p><p>First, we can create the target for our app in the <em>index.html.eex </em>template (delete everything else):</p><pre>&lt;div id=&quot;hello-react&quot;&gt;&lt;/div&gt;</pre><p>Note that the <em>index.html.eex </em>template is nested within <em>app.html.eex</em>. The app template contains a pre-populated header which we can remove:</p><pre>&lt;header class=&quot;header&quot;&gt;<br>  &lt;nav role=&quot;navigation&quot;&gt;<br>    &lt;ul class=&quot;nav nav-pills pull-right&quot;&gt;<br>      &lt;li&gt;&lt;a href=&quot;<a href="http://www.phoenixframework.org/docs">http://www.phoenixframework.org/docs</a>&quot;&gt;Get Started&lt;/a&gt;&lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/nav&gt;<br>  &lt;span class=&quot;logo&quot;&gt;&lt;/span&gt;<br>&lt;/header&gt;</pre><pre>^^^ delete this</pre><p>Now, our React app with be targeted to our <em>index.html.eex </em>template and ultimately nested within <em>app.html.eex</em> and display in our browser.</p><p>Next, let’s define the actual React app.</p><p>Our React application will go in <em>app.js </em>found in the following path:</p><pre>web/static/js/app.js</pre><p>The <em>js </em>folder will be like the root of your React project where you can create your project directory<em>. </em>For example:</p><pre>-- js<br>  -- components<br>  -- scenes<br>  - app.js<br>  - index.html</pre><pre>//etc...</pre><p>We won’t create a project directory in this chapter. Let’s simply add the following into <em>app.js</em>:</p><pre>import &quot;phoenix_html&quot;</pre><pre>import React from &quot;react&quot;<br>import ReactDOM from &quot;react-dom&quot;</pre><pre>class HelloReact extends React.Component {<br>  render() {<br>    return (&lt;h1&gt;Hello React!&lt;/h1&gt;)<br>  }<br>}</pre><pre>ReactDOM.render(<br>  &lt;HelloReact/&gt;,<br>  document.getElementById(&quot;hello-react&quot;)<br>)</pre><p>We can now run mix phoenix.server and see our React application running on <a href="http://localhost:4000/">http://localhost:4000/</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*pA1b3FA7saQa8vNF8Sd9gQ.png" /></figure><p>Woot woot! We are all set to crank out a React application as we traditionally would.</p><h3>Implementing React Router</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0le5eZiFRuLO_B8L-dwKMA.png" /></figure><h4>Explanation</h4><p>The only other thing that I want to walk through is setting up React Router. This will work exactly like any traditional React application. However, I want to clear up any confusion between our <em>Phoenix</em> router and our <em>React</em> Router.</p><p>As we looked at in the previous chapter, we can use the <em>Phoenix </em>router to ultimately control templates that are rendered on different paths.</p><p>Currently, the <em>/ </em>path calls a function called <em>index </em>in a controller called PageController:</p><pre>get &quot;/&quot;, PageController, :index</pre><p>This controller invokes the rendering of the <em>index.html.eex </em>template (with a view specified to make this render).</p><p>The <em>index.html.eex </em>file contains the target of our React application.</p><p>Our React application is a single page application. Meaning, only a single page has to be loaded by the server (as we have it right now).</p><p>The <em>React </em>router is used to update the current URL path shown in the browser for different <strong>views within our single page React application</strong>.</p><p>For example:</p><pre>class App extends React.Component {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;div&gt;<br>          &lt;Route exact path=&quot;/&quot; component={Home}/&gt;<br>          &lt;Route path=&quot;/login&quot; component={Login}/&gt;<strong><br>        </strong>&lt;/div&gt;<strong><br></strong>      &lt;/Router&gt;<br>    )<br>  }<br>}</pre><p>In the example above, the <em>/ </em>path will render a component called <em>Home</em>. The <em>/login </em>path would render a component called <em>Login</em>. The Login component would cause the URL in the browser to look like this:</p><pre><a href="http://localhost:4000/login">http://localhost:4000/login</a></pre><p>Despite the URL being updated, nothing has changed with the server-side routing. The <em>/ </em>path is rendering our entire React application. Because React Router specifies &lt;Route exact path=”/” component={Home}/&gt; in the example above, <a href="http://localhost:4000/login">http://localhost:4000/</a> will display a React component called <em>Home</em>.</p><h4>Implementation</h4><p>To better retain this information, let’s implement React Router in our current Phoenix application that has a React frontend.</p><p>First, we install <em>react-router-dom</em> at the root of our Phoenix project:</p><pre>npm install --save react-router-dom</pre><p>Then, let’s import a Router, Route, and Link into our React application found in <em>app.js</em>:</p><pre>import { BrowserRouter as Router, Route, Link } from &#39;react-router-dom&#39;</pre><p>Let’s also update our render to match the following:</p><pre>render() {<br>  return (<br>    &lt;Router&gt;<br>      &lt;div&gt;<br>        &lt;Route exact path=&quot;/&quot; component={Home}/&gt;<br>        &lt;Route path=&quot;/login&quot; component={Login}/&gt;<br>      &lt;/div&gt;<strong><br></strong>    &lt;/Router&gt;<br>  )<br>}</pre><p>Usually, we would create the two components in separate files. For now, let’s just add the following in <em>app.js </em>above the ReactDOM.render stuff:</p><pre>class Home extends React.Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Hello React!&lt;/h1&gt;<br>        &lt;Link to=&quot;/login&quot;&gt;Login&lt;/Link&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>class Login extends React.Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Hello Boring Login Page!&lt;/h1&gt;<br>        &lt;Link to=&quot;/&quot;&gt;Home&lt;/Link&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><p>Go to <a href="http://localhost:4000/">http://localhost:4000/</a> and we should see this in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*el31V4VRzLQsayRjfkaPQw.gif" /></figure><p>Woohoo! We are routing different views within our React application <em>on the client-side </em>even though only a single route is defined to render this single page React application <em>on the server-side</em>.</p><h3>Final Code</h3><p><a href="https://github.com/michaelmang/full-stack-react-phoenix/tree/master/helloreact">Available via GitHub.</a></p><h3>Concluding Thoughts</h3><p>As you can see, creating a React frontend within a Phoenix project is quite simple. Pardon the boring examples so far, we are about to crank up the power of Phoenix and React by introducing data from a PostgreSQL database.</p><h3>Chapter 5</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-5-working-with-postgresql-83ec4f3286b2">Chapter 5 is now available.</a></p><h3>Sign Up for Notifications</h3><p><a href="http://codingartist.io/full-stack-react-phoenix/">Get notified when each chapter is released.</a></p><p>Cheers,<br>Mike Mangialardi<br>Founder of Coding Artist</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=716979133669" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-4-implementing-react-716979133669">Full-Stack React With Phoenix (Chapter 4 | Implementing React)</a> was originally published in <a href="https://medium.com/coding-artist">Coding Artist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack React With Phoenix (Chapter 3 | Introduction to Phoenix)]]></title>
            <link>https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4?source=rss----6df8bca0c0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/9058de1ff5d4</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Michael Mangialardi]]></dc:creator>
            <pubDate>Wed, 26 Jul 2017 12:56:44 GMT</pubDate>
            <atom:updated>2017-08-01T21:07:58.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0O2VoV2EKXhOb8uKt7JGA.png" /></figure><h3>Table of Contents</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Chapter 1 | Why Bother?</a><br><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Chapter 2 | Learning the Basics of Elixir</a></p><h3>Before We Begin</h3><p><a href="http://www.phoenixframework.org/docs/installation">Install Phoenix by following the official documentation.</a></p><p>Install an Elixir plugin for your code editor of choice. I’m using <a href="https://atom.io/">Atom</a>.</p><p><strong>Important Note:</strong> Since writing this book, Phoenix has had a big update to version 1.3. I will be using version 1.2.4 in this book. You can read more about the upgrade <a href="https://gist.github.com/chrismccord/71ab10d433c98b714b75c886eff17357">here</a>.</p><h3>Scope of This Chapter</h3><p>As the title indicates, the point of this chapter will be to get an introduction to Phoenix.</p><p>I’ve contemplated the best way to go about this. There are two common teaching styles that I’m not a huge fan of. On one hand, sometimes there are a ton of terminologies and high-level concepts before looking at any code which usually doesn’t retain well. On the other hand, coding can be rushed into while an explanation is lacking turning it into a copy and paste session.</p><p>In order to combat both extremes, we will begin by firing up a Phoenix project but carefully explain all the concepts and terminologies as we make a “Hello Phoenix” application.</p><h3>Firing Up a Phoenix Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IAcqnyj7OCk_STAYBMRsaw.png" /></figure><p>It’s important to begin by mentioning we are going to be running a lot of commands that use mix. When working with JavaScript applications, you are used to installing packages, running scripts, and other stuff using npm and node. When dealing with Elixir stuff, the equivalent is to use mix.</p><p>With that aside, let’s get started.</p><p>We can generate a new Phoenix project by running the following command:</p><pre>mix phoenix.new hello_phoenix</pre><p>In the line above, <em>hello_phoenix </em>is the name of our application. This line is like running the Express.js generator:</p><pre>express</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*zocShtI8Yhs-mBFaQ91guw.png" /></figure><p>We can see that a bunch of files were generated for our application. It also asks us to fetch and install dependencies. Type <em>y</em>.</p><p>Once that finishes, we should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkZk4KLEdxZ_tlSVOUXocw.png" /></figure><p>We can see that it ran mix deps.get and some npm install stuff.</p><p><em>Wait a second. I thought this wasn’t JavaScript? What’s going on?</em></p><p>Before we unpack that, run cd hello_phoenix and open the project a text editor. Open <em>mix.exs</em>.</p><p>This file is the equivalent of <em>package.json </em>as it configures our project.<em> </em>There are just a few things to point out.</p><p>The following code contains meta data about our project:</p><pre>def project do<br>  [app: :hello_phoenix,<br>   version: &quot;0.0.1&quot;,<br>   elixir: &quot;~&gt; 1.2&quot;,<br>   elixirc_paths: elixirc_paths(Mix.env),<br>   compilers: [:phoenix, :gettext] ++ Mix.compilers,<br>   build_embedded: Mix.env == :prod,<br>   start_permanent: Mix.env == :prod,<br>   aliases: aliases(),<br>   deps: deps()]<br>end</pre><p>This block of code defines our Elixir dependencies:</p><pre>defp deps do<br>  [{:phoenix, &quot;~&gt; 1.2.4&quot;},<br>   {:phoenix_pubsub, &quot;~&gt; 1.0&quot;},<br>   {:phoenix_ecto, &quot;~&gt; 3.0&quot;},<br>   {:postgrex, &quot;&gt;= 0.0.0&quot;},<br>   {:phoenix_html, &quot;~&gt; 2.6&quot;},<br>   {:phoenix_live_reload, &quot;~&gt; 1.0&quot;, only: :dev},<br>   {:gettext, &quot;~&gt; 0.11&quot;},<br>   {:cowboy, &quot;~&gt; 1.0&quot;}]<br>end</pre><p>When we ran mix phoenix.new hello_phoenix, this file (among others) was generated. Then, it asked us if we wanted to fetch and install these dependencies.</p><p>When we accepted, it ran mix deps.get which is the equivalent of running npm install with a pre-populated <em>package.json </em>file. It installed all of the defined dependencies in the <em>deps </em>folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*vEBCia7SnOiYLDvwr153XA.png" /></figure><p>What about that npm install command that also ran?</p><p>Here is where we have to make clarifications. When using a Node framework like Express, the project directory looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*2PkSU8FEfIMeD1JHMP_G9w.png" /></figure><p>The <em>public </em>folder can contain static images, JavaScript files, and stylesheets. In our Phoenix project, the <em>static </em>folder is the equivalent of this. This stuff is default web technology for the client side and is not the point of difference between Node.js and Phoenix.</p><p>The difference lies in what programming language is used to handling all the server-side coding. In Node.js, this is JavaScript. Therefore, all the dependencies can be specified in <em>package.json </em>and installed via npm. In Phoenix, the server-side code is written in Elixir. Therefore, we need to use mix.deps for the server-side dependencies and npm for the client side dependencies.</p><p>All that to say, the Phoenix generator initially created a pre-populated <em>package.json </em>file with the client-side dependencies specified and upon our approval went ahead and npm installed these dependencies.</p><p>The second half of the line containing the npm install command was node node_modules/brunch/bin/brunch build. Phoenix uses <a href="http://brunch.io/">Brunch.io</a> out of the box for asset management. This is simply an alternative to Webpack. brunch build builds the client side project.</p><p>You can look at <em>brunch-config.js </em>and the <a href="http://brunch.io/">official Brunch.io documentation</a> if you are curious to learn more. However, we won’t be focusing on this until the next chapter. Just remember, there are dependencies and configurations for both the client-side and server-side. The client-side will be a React application in this book. The server-side will be using Elixir code.</p><p>With these explanations aside, run mix phoenix.server to run our application which now available at <a href="http://localhost:4000/">http://localhost:4000/</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXIPe7qAyhJ_wRP4r5_fGQ.png" /></figure><p>As you can see, there is a pre-populated web page. Let’s unpack all the server-side code that is producing this page and then how we can create a new page that renders “Hello Phoenix”.</p><p><strong>Note: </strong>There are hideous errors constantly being spewed in command line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRTF_QP04VylvaIdlfamzQ.png" /></figure><p>This is because we ignored database configuration. However, there’s no need to do that until later on this book so just open a new tab and ignore.</p><h3>Exploring Phoenix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RFphYfnCYdcCFdeN7Ahjw.png" /></figure><h4>Disclaimer</h4><p>As we unpack the generated code and create our “Hello Phoenix” app, I want to make it very clear that you’re not the only one who may be overwhelmed with all the generated files and folders. When I learned React, for example, I purposely ditched <em>create-react-app</em> or any other template so that I could build the entire project from scratch. While I would prefer to be able to do that with Phoenix, there’s just simply not enough time and energy to do that. We are going to have to approach this as “I only am going to care about what I need to know at the moment” so bear with me.</p><h4>Overview</h4><p>In the absolute broadest sense, the starting point of our project is a connection and the end point is a rendered application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSbfveR2mVqQBXKq5o7Pcg.png" /></figure><p>A user connects via a URL and an application is rendered for them to access. This is pretty straightforward. However, we can get more specific.</p><p>There are 5 major <em>layers </em>that are passed through between the connection and the resulting application:</p><ol><li>Endpoint</li><li>Router</li><li>Controllers</li><li>Views</li><li>Templates</li></ol><p>We will unpack each of these layers in order. As we will see, all of these layers are modules containing functions. Given that Elixir is a functional programming language, this entire process can be seen as calling functions until we have our application rendered.</p><h4>Endpoint</h4><p>The endpoint is the first layer contacted after a connection. The endpoint code can be found in <em>lib/hello_phoenix/endpoint.ex</em>. In this file, we just need to know the gist of what’s happening.</p><p>With a quick scan, you will frequently see plug Plug. These are <em>plugs </em>in action. Plugs come from an Elixir dependency called <a href="https://hexdocs.pm/plug/readme.html"><em>Plug</em></a>. You can simply think of Plug as a library of pre-existing modules and functions which we can “plug” into Phoenix to do common server-side stuff in web applications.</p><p>Let’s go through the important plugs in <em>endpoint.ex </em>so we get what’s going on.</p><p>First, plug Plug.Static serves the static files found in our <em>static </em>folder (web/static). Static files include images, JavaScript files, and stylesheets.</p><p>Then, plug Plug.RequestId and plug Plug.Logger are used to log information about requests.</p><p>plug Plug.Parsers allows for parsing the body of request for different content types.</p><p>plug Plug.Session stores the session in a cookie with a signature. This information could be used to store relevant information about sessions in a database.</p><p>After all this, we dispatch requests to a router using plug HelloPhoenix.Router. Router is a very important layer which we will examine next.</p><h4>Router</h4><p>You can open up the router file called <em>router.ex </em>directly under the <em>web </em>folder. The code that looks the most intimidating is the pipeline blocks:</p><pre>pipeline :browser do<br>  plug :accepts, [&quot;html&quot;]<br>  plug :fetch_session<br>  plug :fetch_flash<br>  plug :protect_from_forgery<br>  plug :put_secure_browser_headers<br>end</pre><pre>pipeline :api do<br>  plug :accepts, [&quot;json&quot;]<br>end</pre><p>A pipeline is actually quite simple. A pipeline organizes functions together so you can carry out a task on certain requests.</p><p>These pipelines are called where the requests are handled such as the following:</p><pre>scope &quot;/&quot;, HelloPhoenix do<br>  pipe_through :browser # Use the default browser stack</pre><pre>  get &quot;/&quot;, PageController, :index<br>end</pre><p>In the code above, we are handling requests in the scope of the root path of our application. On the root path, we want to <em>get</em> content which requires passing through the PageController, and specifically, running the <em>index </em>function within it (more on this shortly).</p><p>Before that, however, we can say: “Pipe through the browser pipeline so we can use the default browser stack. Then, go ahead and get the content on this path by passing through to the controller.”</p><p>A quick note. You may have seen a lot of atoms (i.e. :browser) being used in the Phoenix code. Here, we have a really clear example of how atoms can be used to call functions:</p><pre>pipe_through :browser</pre><p>Anyways, it’s time to go on to the next layer which is controllers. In the code we had above, we specifically want to pass through to the <em>PageController </em>and run the <em>index </em>function in it.</p><h4>Controllers</h4><p>The basic usage of a controller is to invoke rendering of a view.</p><p>In <em>web/controllers/page_controller.ex</em>, the index function takes the connection and renders <em>index.html</em>:</p><pre>def index(conn, _params) do<br>  render conn, &quot;index.html&quot;<br>end</pre><p>You’ll notice _params is grayed out. This would be updated if we had incoming parameters passed down from the router. We will look at an example of doing that later on in this chapter.</p><p>The &quot;index.html&quot; corresponds with a template. However, there needs to be a view for each template so we will look at that next.</p><h4>View</h4><p>Views have the shortest amount of code but they were the hardest thing to wrap my mind around. For example, the flow between the router and controller was pretty clear. There was an explicit call to a function within a controller from the router on a certain request:</p><pre>get &quot;/&quot;, PageController, :index</pre><p>However, in our controller, we invoked the rendering of <em>index.html</em>:</p><pre>render conn, &quot;index.html&quot;</pre><p>The <em>index.html </em>that is being invoked is defined in a template file under <em>web/templates/page/index.html.eex</em>.</p><p>While there is no explicit call to a function or anything that would indicate a flow into writing a view file, a view file is expected for each template invoked by a controller. The view file will do the actual rendering of the template.</p><p>Think of it this way, I’m sure there’s been a time in your life when someone moved you to do something without saying words and giving you a certain look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*lgxSQ583jofn4LRpcpuFDg.png" /></figure><p>We could call this an <em>implicit </em>form of communication.</p><p>In the same way, the controller invokes a view to render <em>implicitly </em>when it runs:</p><pre>render conn, &quot;index.html&quot; # or any other template</pre><p>However, you’ll see that there are several pre-populated views in our project. How do we know which view (that is implicitly being told to render a template) is associated with our <em>PageController</em>?</p><p>Well, the naming is very important. Since we have a controller called <em>PageController</em>, Phoenix will expect a view called <em>PageView</em>. The association is through the name. Additionally, there should be a folder underneath the <em>templates </em>folder called <em>page </em>which contains the template being invoked. We can see this in our project directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*ArrKS37aae0LVfnLY6z1fQ.png" /></figure><p>Let’s look at <em>page_view.ex</em>:</p><pre>defmodule HelloPhoenix.PageView do<br>  use HelloPhoenix.Web, :view<br>end</pre><p>In this file, all that is needed to cause a template to render is the following line:</p><pre>use HelloPhoenix.Web, :view</pre><p>With all this aside, let’s move on to looking at the template.</p><h4>Template</h4><p>The <em>index.html.eex </em>file looks like just normal HTML. However, because this is a template, we can do some special things such as can be seen in the following line:</p><pre>&lt;h2&gt;&lt;%= gettext &quot;Welcome to %{name}&quot;, name: &quot;Phoenix!&quot; %&gt;&lt;/h2&gt;</pre><p><a href="https://hexdocs.pm/gettext/Gettext.html"><em>gettext</em></a><em> </em>is an Elixir dependency which just provides a module that is being used to inject a name. You can change the value of name and see the changes reflected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6K4j_Kmz_3IpU0RbEm_dQ.png" /></figure><p>A generated Phoenix project also contains an app template found in <em>app.html.eex</em>.</p><p>There’s no controller for invoking this template as it is not attached to any request and is used to nest views:</p><pre>&lt;main role=&quot;main&quot;&gt;<br>  &lt;%= render <a href="http://twitter.com/view_module">@view_module</a>, <a href="http://twitter.com/view_template">@view_template</a>, assigns %&gt;<br>&lt;/main&gt;</pre><p>There are a few other things here worth mentioning.</p><p>There’s some paragraph tags which output errors for us if something goes wrong:</p><pre>&lt;p class=&quot;alert alert-info&quot; role=&quot;alert&quot;&gt;&lt;%= get_flash(<a href="http://twitter.com/conn">@conn</a>, :info) %&gt;&lt;/p&gt;<br>&lt;p class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;&lt;%= get_flash(<a href="http://twitter.com/conn">@conn</a>, :error) %&gt;&lt;/p&gt;</pre><p>There’s also the inclusion of our <em>app.js </em>file in our <em>static </em>folder which does nothing right now:</p><pre>&lt;script src=&quot;&lt;%= static_path(<a href="http://twitter.com/conn">@conn</a>, &quot;/js/app.js&quot;) %&gt;&quot;&gt;&lt;/script&gt;</pre><p>You can also see how static file paths are referenced.</p><p>Everything is worth keeping except for the header which we can remove:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXCixvn7WtetcfKemWXfrw.png" /></figure><p>Now, the only thing rendering is the <em>index </em>template.</p><p>What if we request the following?</p><p><a href="http://localhost:4000/hello">http://localhost:4000/hello</a></p><p>We get an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1kfxmB4AuVU5lf1OQvtI5g.png" /></figure><p>Let’s use this path to display “Hello Phoenix” using a parameter in the path as data.</p><h3>Hello Phoenix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0lnfJGrx2a_DYCR9IB8Ng.png" /></figure><p>First, open up <em>router.ex </em>and let’s get some content on a new path:</p><pre>scope &quot;/&quot;, HelloPhoenix do<br>  pipe_through :browser # Use the default browser stack</pre><pre>  get &quot;/&quot;, PageController, :index<br>  get &quot;/hello/:data&quot;, HelloController, :message<br>end</pre><p>:data specifies a dynamic parameter that will be passed to our <em>HelloController</em>. So, <em>/users/phoenix </em>would pass <em>phoenix.</em></p><p>We specifically want to call the <em>message function </em>within this controller.</p><p>Next, let’s create a controller called <em>hello_controller.ex </em>within the <em>controllers </em>folder:</p><pre>defmodule HelloPhoenix.<strong>HelloController</strong> do<br>  use HelloPhoenix.Web, :controller</pre><pre>  def <strong>message</strong>(conn, _params) do<br>    render conn, <strong>&quot;hello.html&quot;</strong><br>  end<br>end</pre><p>Based off of the existing <em>PageController</em>, we just need to make some slight tweaks.</p><p>In addition, we also assign the params in a map:</p><pre>def message(conn, %{&quot;data&quot; =&gt; data}) do</pre><p>This makes our params (data) easily accessible through an associative collection.</p><p>On top of this, we also need to make <em>data </em>accessible in our template like so:</p><pre>render conn, &quot;hello.html&quot;, data: data</pre><p>Before we create the template, first we create a view in a file called <em>hello_view.ex</em>:</p><pre>defmodule HelloPhoenix.HelloView do<br>  use HelloPhoenix.Web, :view<br>end</pre><p>Now, we can create a folder for our template within the <em>templates </em>folder called <em>hello</em>. Then, create a file called <em>hello.html.eex</em>.</p><p>In here, we simply can inject our data into a message:</p><pre>&lt;div class=&quot;jumbotron&quot;&gt;<br>  &lt;h2&gt;&lt;%= @data %&gt;&lt;/h2&gt;<br>&lt;/div&gt;</pre><p>&lt;%= %&gt; surrounds Phoenix stuff in HTML. @data is used to inject our data param.</p><p>Woot woot! We are all done!</p><p>Type in <a href="http://localhost:4000/hello/phoenix">http://localhost:4000/hello/phoenix</a> to see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qL8NQFqEkPHbL8jOloCMvw.png" /></figure><p>If we do <a href="http://localhost:4000/hello/elixir">http://localhost:4000/hello/elixir</a>, we can see it update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RobNmBcO_ucP3SgIn6mVrQ.png" /></figure><p>Sweet! Round of applause!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*L8nLPhXvLMmYzGQ9WLxgqA.gif" /></figure><p>Before we wrap things up, let’s recap the follow from our connection to rendering an application.</p><p>First, gather some info and other stuff through an <strong>endpoint</strong> using plugs.</p><p>Then, the <strong>router</strong> can handle different requests and call a function within a <strong>controller</strong>.</p><p>The <strong>controller</strong> invokes the rendering of a template and implicitly expects a <strong>view</strong> to be added.</p><p>The view allows for the rendering of a <strong>template</strong>.</p><p>The template can define HTML and inject data.</p><p>Views are all nested within the <em>app.html.eex</em> template.</p><h3>Final Code</h3><p><a href="https://github.com/michaelmang/full-stack-react-phoenix/tree/master/hello_phoenix">Available on GitHub.</a></p><h3>Concluding Thoughts</h3><p>Phoenix is pretty intimidating to start, not going to lie. However, I hope this has been a good explanation as I’ve had many “a-ha” moments as I wrote this.</p><p>In the next chapter, we will implement a React frontend in our Phoenix application.</p><h3>Chapter 4</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-4-implementing-react-716979133669">Chapter 4 is now available.</a></p><h3>Sign Up for Notifications</h3><p><a href="http://codingartist.io/full-stack-react-phoenix/">Get notified when each chapter is released.</a></p><p>Cheers,<br>Mike Mangialardi<br>Founder of Coding Artist</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9058de1ff5d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4">Full-Stack React With Phoenix (Chapter 3 | Introduction to Phoenix)</a> was originally published in <a href="https://medium.com/coding-artist">Coding Artist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack React With Phoenix (Chapter 2 | Learning the Basics of Elixir)]]></title>
            <link>https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59?source=rss----6df8bca0c0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/f9010fac8c59</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Michael Mangialardi]]></dc:creator>
            <pubDate>Tue, 25 Jul 2017 12:31:30 GMT</pubDate>
            <atom:updated>2017-07-26T13:31:39.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiC2xMlEVIkaDuBwgtKPAg.png" /></figure><h3>Previous Chapters</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Chapter 1 | Why Bother?</a></p><h3>Scope of This Chapter</h3><p>As I mentioned in the previous chapter, learning Phoenix is awesome because we can learn Elixir (the language it is built off of) in the process. However, this also means we have to put in a bit more effort before we dive into Phoenix to understand all the fundamentals of this new programming language.</p><p>Elixir is a functional programming language at its core which has some awesome features to pack a lot of punch in shorter amounts of code.</p><p>In this chapter, we will be following the main structure and types of examples as <a href="https://elixirschool.com/en/">Elixir School</a> which is a great resource for referencing the basics of Elixir in bite-sized lessons. Instead of reinventing the wheel, this chapter will be like a practical commentary on this resource.</p><p>Not only do I hope that this chapter is a practical guide to learn Elixir, but I also hope you see that Elixir is a lot of fun!</p><p>Let’s get started.</p><h3>Before We Begin</h3><p>Make sure to <a href="https://elixir-lang.org/install.html">install Elixir by following the official instructions</a>.</p><p>You can check to make sure you have Elixir installed properly by running the following in command line:</p><pre>elixir -v</pre><p>If it is installed correctly, we can run Elixir code in an interactive shell which you should now fire up by running:</p><pre>iex</pre><p><strong>Another note:</strong> I was going to cover the question of “What is functional programming?” since Elixir is a functional language. I am just going to punt to <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0">this great article by Eric Elliot</a> if you are unfamiliar.</p><h3>Data Types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGiLT3yR2Hfua3A2fSyRbg.png" /></figure><p>Here is a comparison between the basic Elixir data types and the JavaScript data types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4kVkuxpSYbSB34mrtsYYQ.png" /></figure><p>Let’s use the interactive mode in command line to test out go over these basic Elixir data types.</p><p><strong>Integers</strong></p><p><strong>Integers</strong> are whole numbers. In Elixir, they can be negative or positive:</p><pre>&gt; 2 + 2<br>4</pre><pre>&gt; -2 + 2<br>0</pre><p><strong>Floats</strong></p><p><strong>Floats</strong> are numbers with at least one decimal place:</p><pre>&gt; 2.0 + 3.4<br>5.4</pre><p>They can also be expressed in exponential form:</p><pre>&gt; 1.0e-9<br>1.0e-9</pre><p>Think scientific notation from your high school math class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*jW6wVxu8TLgTgpEsKw2qOA.png" /></figure><h4>Basic Arithmetic</h4><p>Now that we now our two number types, let’s try some example of basic arithmetic:</p><pre>&gt; 2 + 2<br>4</pre><pre>&gt; 2.0 + 4<br>6.0</pre><pre>&gt; 2 - 4<br>-2</pre><pre>&gt; 2.0 - 4<br>-2.0</pre><pre>&gt; 2 * 3<br>6</pre><pre>&gt; 2 * 4.0<br>8.0</pre><pre>&gt; 2 / 2<br>2.0</pre><pre>&gt; 2/1.1<br>1.818181...</pre><p>In the first example, we do simple addition between two integers and the result is an integer. However, the next example shows us that a float plus an integer results in a float.</p><p>We see the same thing in the next few examples for subtraction and multiplication.</p><p>Division is a bit different. 2 / 2 results in a float, 2.o. In order to integer division, div must be used:</p><pre>&gt; div(2,2)<br>1</pre><pre>&gt; div 2,2<br>1</pre><p>We can also get the remainder by using rem:</p><pre>&gt; rem 26,5<br>1</pre><p>If the rem example seems odd, here’s a visualization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*3CfXiJSKMi56MyybUuU3uQ.png" /></figure><p>Finally, let’s use round a float to an integer like so:</p><pre>&gt; round(2.2)<br>2</pre><h4>Booleans</h4><p>Just like JavaScript, <strong>Booleans</strong> are true or false:</p><pre>&gt; true<br>true</pre><pre>&gt; false<br>false</pre><p>The only thing that isn’t true (besides false) is nil:</p><pre>&gt; nil<br>nil</pre><h4>Atoms &amp; Modules</h4><p><strong>Atoms</strong> are constants whose <em>names </em>are also their <em>values</em>:</p><pre>&gt; :test<br>:test</pre><pre>&gt; :test == :compare<br>false</pre><p>In JavaScript, the equivalent to these are symbols which were introduced in ES6:</p><pre>var sym = Symbol(&#39;foo&#39;);</pre><p>Their only purpose in JavaScript is to be an identifier of object properties.</p><p>In Elixir, names of modules<strong> </strong>are also atoms.</p><p><strong>Modules</strong> are namespaces for functions. We will look at these later in this chapter. However, if we had a <em>module </em>called <em>Test </em>and a <em>function</em> within that module called <em>func</em>, we would call it like so (don’t run this):</p><pre>&gt; Test.func<br>*result from function*</pre><p>Even <em>Test </em>has not been declared yet, it will also be an atom:</p><pre>&gt; is_atom(Test)<br>true</pre><p>Atoms can also be used to reference external and built-in Erlang libraries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*VTr-j5L2a0BO7maGj9wqMg.png" /></figure><h4>Strings</h4><p><strong>Strings</strong> are pretty easy to grasp. However, strings must be in double quotes:</p><pre>&gt; &quot;string&quot;<br>&quot;string&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*8hq2JItOkVnSPpii2Z2O1w.png" /></figure><p>We can <em>print</em> strings using IO.puts (stands for input/output):</p><pre>&gt; IO.puts &quot;hello&quot;<br>hello<br>:ok</pre><p>As you can see, printing a string also the atom :ok.</p><p>We can also use IO.gets to capture a string from an input:</p><pre>&gt; myFav = IO.gets &quot;Elixir or JavaScript?\n&quot;<br>Elixir or JavaScript? //prompt<br>Elixir //what we type in<br>&quot;Elixir\n&quot; //captured string<br>&gt; myFav<br>&quot;Elixir\n&quot;</pre><p>In the code above, we display a prompt, type in our response, see the captured string, and then check the value of myFav which is Elixir\n.</p><p>\n puts in a new line when we print. You can think of this like &lt;br/&gt; in HTML.</p><p>We can see this in action by printing myFav:</p><pre>&gt; IO.puts myFav<br>Elixir</pre><pre>:ok</pre><p>The equivalent of the + (JavaScript) for string concatenation in Elixir is &lt;&gt;:</p><pre>&gt; IO.puts &quot;Hello&quot; &lt;&gt; &quot; World&quot;<br>Hello World<br>:ok</pre><h4>Comparison Operators</h4><p>Let’s take a moment to look at <strong>comparison operators</strong>. There is nothing too unusual for a JavaScript developer:</p><pre>&gt; 2 == 2.0<br>true</pre><pre>&gt; 2 === 2.0<br>false</pre><pre>&gt; 2 &gt; 3<br>false</pre><pre>&gt; 2 &lt; 4<br>true</pre><pre>&gt; 2 &lt;= 2<br>true</pre><pre>&gt; 4 &gt;= 3<br>true</pre><pre>&gt; 2 != 2<br>false</pre><pre>&gt; 2 !== 2.0<br>true</pre><p>=== and !== are <em>strict </em>comparisons that check the type and value. As we saw in the examples above,</p><p>2 === 2.0 is false because Elixir has integers and floats unlike JavaScript which simply has number.</p><p>We can also do string comparison of any types:</p><pre>&gt; 2 === &quot;string&quot;<br>false</pre><h4><strong>Lists</strong></h4><p><strong>Lists </strong>are collections of values that can contain multiple types within brackets:</p><pre>&gt; list = [1, &quot;a&quot;, :test]<br>[1, &quot;a&quot;, :test]</pre><pre>&gt; list<br>[1, &quot;a&quot;, :test]</pre><p>In Elixir, lists are implemented as <em>linked lists</em>. Linked lists are linear data structures where each element is a separate node. [<a href="https://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html">1</a>]</p><p>Visually, they would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RiXlpSk04xqm7VOGq-maw.png" /></figure><p>In order to read all the values within a linked list, we <em>traverse </em>from the head to the end (where next is null). The <em>head</em> is the first value and the rest of the list is the <em>tail</em>.</p><p>We can do some cool things with lists such as concatenation using ++:</p><pre>&gt; list = [1,2] ++ [3,4]<br>[1, 2, 3, 4]</pre><p><strong>Note: </strong>In most cases, you should concatenate a value to the front of a list (prepend) like so:</p><pre>&gt; list = [1,2,3]<br>[1, 2, 3]</pre><pre>&gt; [&quot;soup&quot;] ++ list<br>[&quot;soup&quot;, 1, 2, 3]</pre><p>We can also subtract from lists like so:</p><pre>&gt; list -- [1,2]<br>[3, 4]</pre><p>Another cool feature is that we can easily extract the head and tail of a list using hd and tl:</p><pre>&gt; hd [3,2,1]<br>3</pre><pre>&gt; tl [3,2,1]<br>[2,1]</pre><p>We can also store the head and tails values from lists really easily using <em>pattern matching</em>:</p><pre>&gt; [storeA | storeB] = [1, &quot;chicken&quot;, &quot;soup&quot;]<br>[1, &quot;chicken&quot;, &quot;soup&quot;]</pre><pre>&gt; storeA<br>1</pre><pre>&gt; storeB<br>[&quot;chicken&quot;, &quot;soup&quot;]</pre><h4>Tuples</h4><p>According to Elixir School, “Tuples are similar to lists but are stored contiguously in memory.” I’m sure that might not make sense to everyone right away, so <a href="https://elixir-lang.org/getting-started/basic-types.html#lists-or-tuples">here’s the full explanation</a>.</p><p>Tuples also look much like lists, however, they are within curly braces:</p><pre>{3.14, :pie, &quot;Apple&quot;}</pre><p>One important use of tuples is that they can be returned from functions.</p><p>We can extract a value in a tuple using elem(*tuple*, *index*):</p><pre>&gt; tuple = {1,2}<br>{1, 2}</pre><pre>&gt; elem(tuple, 0)<br>1</pre><p>Notice that the index starts at 0.</p><h4>Keyword Lists</h4><p><strong>Keyword lists </strong>are lists that associate a key with a value:</p><pre>&gt; [chicken: &quot;noodle&quot;, soup: &quot;is lit&quot;]<br>[chicken: &quot;noodle&quot;, soup: &quot;is lit&quot;]</pre><p>In the example above, chicken:<em> </em>and soup:<em> </em>are both atoms. chicken: “noodle” and soup: “is lit” are both tuples.</p><p>The example could also be written like so:</p><pre>&gt; [{:chicken, &quot;noodle&quot;}, {:soup, &quot;is lit&quot;}]<br>[chicken: &quot;noodle&quot;, soup: &quot;is lit&quot;]</pre><h4>Maps</h4><p><strong>Maps</strong> are another associative collection (store with key and value association). Maps are defined with %{}:</p><pre>&gt; example <strong>=</strong> %{:hey <strong>=&gt;</strong> &quot;you&quot;, &quot;squadron&quot; <strong>=&gt;</strong> :up}<br>%{:hey =&gt; &quot;you&quot;, &quot;squadron&quot; =&gt; :up}</pre><pre>&gt; example[:hey]<br>&quot;you&quot;</pre><pre>&gt; example[&quot;squadron&quot;]<br>:up</pre><p>We can also fetch a value which is store in a tuple with a preceding :ok atom:</p><pre>&gt; Map.fetch(example, :hey)<br>{:ok, &quot;you&quot;}</pre><h3>Enumerating</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbGqjw_a1zc5B0NuNI6Egg.png" /></figure><p>Elixir comes with a built-in module called Enum which allows us to enumerate through lists, keyword lists, and maps to do some powerful stuff.</p><p>Let’s test this out.</p><h4>Enum.all?</h4><p>We can use <strong>Enum.all? </strong>to enumerate through a collection and return true if every item in the collection meets a condition.</p><p>For example:</p><pre>&gt; list = [&quot;foo&quot;, &quot;bar&quot;, &quot;hello&quot;]<br>[&quot;foo&quot;, &quot;bar&quot;, &quot;hello&quot;]</pre><pre>&gt; Enum.all?(list, fn(item) -&gt; String.length(item) == 3 end)<br>false</pre><p>A couple things to note.</p><p>First, the code above can be read as: “Enumerate through each item in our list and return true if every item is a string with 3 characters.</p><p>Second, note the syntax for this:</p><pre>Enum.all?(*insert list, *anonymous function*)</pre><p>The anonymous function in this example, fn(item) -&gt; String.length(item) == 3 end is just like the following in JavaScript:</p><pre>list.map((item) =&gt; {....})</pre><p>There’s a couple differences:</p><ul><li><em>fn </em>comes before the parameter.</li><li>The arrow is “skinny” not “fat”.</li><li>We don’t need a return statement.</li><li>We end an anonymous function using <em>end</em>.</li></ul><h4>Enum.any?</h4><p>This is similar to the previous example except it will return true if any item meets the condition:</p><pre>&gt; Enum.any?(list, fn(item) -&gt; String.length(item) == 3 end)<br>true</pre><h4>Enum.chunk</h4><p><strong>Enum.chunk </strong>breaks a collection into smaller groups using the following syntax:</p><pre>Enum<strong>.</strong>chunk(*insert collection*, *break into groups of this size*)</pre><p>For example:</p><pre>&gt; Enum.chunk([1, 2, 3, 4], 2)<br>[[1,2], [3,4]]</pre><p><strong>Note:</strong> If there’s not enough items left to form a group with the specified size, the remaining items are omitted:</p><pre>&gt; Enum.chunk(list, 2)<br>[[&quot;foo&quot;, &quot;bar&quot;]]</pre><pre>&gt; list<br>[&quot;foo&quot;, &quot;bar&quot;, &quot;hello&quot;]</pre><p>We can also chunk based on a condition other than size using <strong>Enum.chunk_by</strong>:</p><pre>&gt; Enum.chunk_by(list, fn(item) -&gt; String.length(item) == 3 end)<br>[[&quot;foo&quot;, &quot;bar&quot;], [&quot;hello&quot;]]</pre><p>As you can see above, all three items met the condition and there’s one group of two items and another group with just one item. It always follows this pattern:</p><pre>&gt; Enum<strong>.</strong>chunk_by([&quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;], <strong>fn</strong>(x) <strong>-&gt;</strong> String<strong>.</strong>length(x) <strong>end</strong>)<br>&gt; [[&quot;one&quot;, &quot;two&quot;], [&quot;three&quot;], [&quot;four&quot;, &quot;five&quot;]]</pre><h4>Enum.map_every</h4><p>What if we wanted to go through a collection and do something with every <em>nth </em>item? That’s where <strong>Enum.map_every</strong><em> </em>comes in:</p><pre>&gt; numbers = [1,2,3]<br>[1, 2, 3]</pre><pre>&gt; Enum.map_every(numbers, 2,  fn(number) -&gt; number + 1 end)<br>[2, 2, 4]</pre><p>As you can see, it applies the function on the first item and every <em>nth </em>item after that.</p><h4>Enum.each</h4><p>This is used if we want to iterate through a collection but not create a new collection.</p><p>For example, we can print out a list:</p><pre>&gt; Enum.each(list, fn(item) -&gt; IO.puts(item) end)<br>Foo<br>Bar<br>Hello<br>:ok</pre><h4>Enum.map</h4><p>If we do want to iterate through a collection and create a new collection with updated values, we can use <strong>Enum.map</strong>:</p><pre>&gt; numbers = [1, 2, 3, 4]<br>[1, 2, 3, 4]</pre><pre>&gt; Enum.map(numbers, fn(number) -&gt; number * 2 end)<br>[2, 4, 6, 8]</pre><h4>Enum.min &amp; Enum.max</h4><p>As you can guess, these return the min and max of a collection respectively:</p><pre>&gt; Enum.min(numbers)<br>1</pre><pre>&gt; Enum.max(numbers)<br>4</pre><h4>Enum.reduce</h4><p><strong>Enum.reduce </strong>takes in a collection and an <em>accumulator</em> and “reduces” the collection to a single number. Make sense? <em>No way, Mike!</em></p><p>I figured. Let’s explain by looking at an example:</p><pre>&gt; Enum.reduce([1, 2, 3], 5, fn(item, acc) -&gt; item + acc end)<br>&gt; 11</pre><p>What the shoot?! How did give us 11?!</p><p>Let’s walk through it by each iteration:</p><pre>1) item is 1 and acc is 5. 6 (1 + 5) then becomes the new value of the accumulator.</pre><pre>accumulator: 6</pre><pre>2) item is now 2 and acc is 6. 8 (2 + 6) then becomes the new value of the accumulator.</pre><pre>accumulator: 8</pre><pre>3) item is now 3 and acc is 8. 11 (3 + 8) then becomes the new value of the accumulator.</pre><pre>Final accumulator and final value returned: 11</pre><p>In the example above, a single value is accumulated and returned hence <em>accumulator</em>.</p><p>If no accumulator is specified, it is initialized as 0</p><pre>&gt; Enum.reduce([1, 2, 3], fn(item, acc) -&gt; item + acc end)<br>6</pre><h4>Enum.sort</h4><p>We can use this to sort a collection:</p><pre>&gt; numbers = [4,99,1]<br>[4, 99, 1]</pre><pre>&gt; sorted = Enum.sort(numbers)<br>[1, 4, 99]</pre><pre>&gt; sorted<br>[1, 4, 99]</pre><h4>Enum.uniq</h4><p>The final one to discuss is <strong>Enum.uniq </strong>which simply removes duplicate values:</p><pre>&gt; dups = [4,1,2,1]<br>[4, 1, 2, 1]</pre><pre>&gt; Enum.uniq(dups)<br>[4, 1, 2]</pre><p>As you can see, it removes duplicates from the end.</p><p>That completes the enumerations which showcase how much power we can pack in small pieces of code with functional programming in Elixir.</p><p>Don’t worry. The fun won’t end there.</p><h3>Pattern Matching</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSqQInLcGzsqNjnEIJRQ4Q.png" /></figure><p>So far, there’s been multiple examples where we bound a value to a variable like so:</p><pre>numbers = [1, 2, 3, 4]</pre><p>Well, the = is not what you may be used to in JavaScript and other languages. In addition to binding variables, it can be used to store values from data structures into individual variables.</p><p>Here’s an example:</p><pre>&gt; [a,b,c] = [1,2,3]<br>[1, 2, 3]</pre><pre>&gt; a <br>1</pre><pre>&gt; b<br>2</pre><pre>&gt; c <br>3</pre><p>Neat!</p><p>Now, this only works if both sides are the same size and the same type:</p><pre>&gt; [a,b] = [1,2,3]<br>** (MatchError) no match of right hand side value: [1, 2, 3]</pre><pre>&gt; {a,b,c} = [1,2,3]<br>** (MatchError) no match of right hand side value: [1, 2, 3]</pre><p>The second error is produced because the left-hand collection is a tuple but the right-hand collection is a list.</p><h3>Control Structures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMkBcghj1HXeBIs2KiC72Q.png" /></figure><p>Control structures may sound complicated, but we’re just going to be looking at handling conditions.</p><h3>If/Else</h3><p>An <strong>if/else</strong> has the following syntax in Elixir:</p><pre>if *condition is true* do<br>  //something<br>else<br>  //do something else<br>end</pre><p>Let’s give this a shot:</p><pre>&gt; x = 1<br>1</pre><pre>&gt; y = 2<br>2</pre><pre>&gt; if x === y do<br>...&gt; IO.puts &quot;Cool beans!&quot;<br>...&gt; else<br>...&gt; IO.puts &quot;Oh shoot!&quot;<br>...&gt; end<br>Oh shoot!<br>:ok</pre><p>We could also do if/else if/else which would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*frOhdAZsfU5klM9ngP36Mw.png" /></figure><h4>Unless</h4><p>Here’s a cool control structure distinct from JavaScript.</p><p>We can replace an <em>if </em>with <em>unless </em>like so:</p><pre>&gt; game = &quot;mass effect andromeda&quot;<br>&quot;mass effect andromeda&quot;</pre><pre>&gt; unless game = &quot;mass effect andromeda&quot; do<br>...&gt; IO.puts &quot;Sure! I&#39;ll play!&quot;<br>...&gt; else <br>...&gt; IO.puts &quot;No thanks!&quot;<br>...&gt; end</pre><pre>No thanks!<br>:ok</pre><h4>Case</h4><p><strong>Case</strong> is used to compare a value against many patterns until we find a matching one. It’s similar to a switch in JavaScript.</p><pre>&gt; case [1,2,3] do<br>...&gt; [1,2,3] -&gt; IO.puts &quot;Match!&quot;<br>...&gt; [4,2,3] -&gt; IO.puts &quot;No Match!&quot;<br>...&gt; [1,2,x] -&gt; IO.puts &quot;Match first two items and x would equal 3&quot;<br>...&gt; _ -&gt; IO.puts &quot;Wildcard: match any value&quot;<br>...&gt; [_,_,3] -&gt; IO.puts &quot;Match any value for the first two.&quot;<br>...&gt; end</pre><pre>Match<br>:ok</pre><p>Because you can bind items and use wildcards, this is extremely useful yet beautifully condense.</p><h4>Cond</h4><p>If you want to match conditionals instead of values, use <strong>cond</strong>:</p><pre>&gt; cond do <br>...&gt; 1 === 2 -&gt; &quot;LOL&quot;<br>...&gt; 1 === &quot;pie&quot; -&gt; &quot;It better be cherry!&quot;<br>...&gt; 1 === 1 -&gt; &quot;Squadron up!&quot;<br>...&gt; end<br>&quot;Squadron up!&quot;</pre><h3>Functions, Modules, &amp; Pipe Operator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Woyms74puOtJZ4fyJNzlw.png" /></figure><p><em>The final section…woohoo!</em></p><h4>Anonymous Functions</h4><p>We already discussed anonymous functions which looked like this:</p><pre>increase = fn(number) -&gt; number + 1 end</pre><p>There’s also a shorthand way of writing this:</p><pre>increase = &amp;(&amp;1 + 1)</pre><p>The first &amp; can be thought of as a replacement of fn() -&gt;. &amp;1 refers to the first (and only) parameter which we want to increment by 1 and return. The end is also omitted.</p><h4>Named Functions and Modules</h4><p>For a named function, we write that within a module which we already mentioned is a namespace for one or more functions:</p><pre>defmodule Animals do<br>  def dog(name) do<br>    &quot;Bark bark &quot; &lt;&gt; name<br>  end<br>  def cat(name) do<br>    &quot;Meow meow &quot; &lt;&gt; name<br>  end<br>end</pre><p>defmodule defines a module which we called <em>Animals</em>. Within it, we have two functions, <em>dog </em>and <em>cat</em>, which are proceeded with def.</p><p>To call our functions, we would do:</p><pre>&gt; Animals.dog(&quot;Max&quot;)<br>&quot;Bark bark Max&quot;</pre><pre>&gt; Animals.cat(&quot;Daisy&quot;)<br>&quot;Meow meow Daisy&quot;</pre><p><strong>Important Note: </strong>You must keep module names capitalized and named functions lowercase.</p><h4>Pipe Operator</h4><p>In our code, we will have multiple functions. There will be many cases when we want to take the result of one function and use it as a parameter for another function.</p><p>Here’s one way we could write it:</p><pre>//HelloWorld.hello returns &quot;Hello&quot;<br>//myModule.world(param) returns param &lt;&gt; &quot; World&quot;</pre><pre>&gt; HelloWorld.world(myModule.hello)<br>&quot;Hello World&quot;</pre><p>Now, this isn’t <em>too </em>confusing for a simple example. However, there’s a cleaner way to write this using the pipe operator, |&gt;:</p><pre>&gt; HelloWorld.hello |&gt; HelloWorld.world<br>&quot;Hello World&quot;</pre><p>Here’s the full example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMqu0WFH-q6-rfxtRdXXfA.png" /></figure><p>We can also use this to simply separate parameters from functions:</p><pre>&gt; &quot;hello&quot; |&gt; HelloWorld.world<br>&gt; &quot;Hello World&quot;</pre><h3>Extra Practice</h3><p>That’s all she wrote! We have completed a walk through of the basics of Elixir. Hopefully, this was fun and exciting. We should have all we need to dabble into Phoenix, however, I would encourage you to play around and do some exercises.</p><p>I recommend finding <a href="https://www.google.com/search?q=python+practice+problems&amp;oq=pyth&amp;aqs=chrome.2.69i57j69i59l3j0l2.2547j0j4&amp;sourceid=chrome&amp;ie=UTF-8">Python practice problems</a> and completing them with Elixir.</p><h4>Other Resources:</h4><p><a href="https://elixirschool.com/en/lessons/basics/mix/">Elixir School</a><br><a href="https://elixir-lang.org/getting-started/introduction.html">Getting Started Guide</a><br><a href="https://elixir-lang.org/docs.html">Official Docs</a><br><a href="http://amzn.to/2usT8S9">Programming Elixir</a></p><p>Happy Hacking! 💪</p><h3>Up Next</h3><p>In the next chapter, we will go an introduction into the concepts and terminologies behind Phoenix and complete our first Phoenix app together.</p><h3>Chapter 3</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4">Chapter 3 is now available.</a></p><h3>Sign Up for Notifications</h3><p><a href="http://codingartist.io/full-stack-react-phoenix/">Get notified when each chapter is released.</a></p><p>Cheers,<br>Mike Mangialardi<br>Founder of Coding Artist</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9010fac8c59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Full-Stack React With Phoenix (Chapter 2 | Learning the Basics of Elixir)</a> was originally published in <a href="https://medium.com/coding-artist">Coding Artist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack React With Phoenix (Chapter 1 | Why Bother?)]]></title>
            <link>https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf?source=rss----6df8bca0c0de---4</link>
            <guid isPermaLink="false">https://medium.com/p/d3c4a38846cf</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Michael Mangialardi]]></dc:creator>
            <pubDate>Mon, 24 Jul 2017 22:03:14 GMT</pubDate>
            <atom:updated>2017-08-31T15:36:11.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-psuommoqb5mSyfw7krrA.png" /></figure><h3>Prerequisites</h3><p>First off, understand the fundamentals of React, ES6, and the basic build of a React application (NPM, Webpack, Babel).</p><p>If you have not learned React yet, here is a book I wrote called <a href="https://leanpub.com/reactjsforthevisuallearner">React.js for the Visual Learner</a>.</p><p>While not technically a mandatory prerequisite to go through this book, it is highly recommended to understand basic full-stack React development with Node.js and a database. I recommend checking out <a href="https://medium.com/coding-artist/redux-from-scratch-chapter-7-building-an-api-service-with-express-js-mongodb-3bde96e1f45b">Chapter 7 from my book called Redux From Scratch</a> if you need to get caught up to speed.</p><h3>What to Expect</h3><p>As the title implies, Phoenix is a web framework for writing backend (server-side) code that provides an alternative to Node.js backend frameworks. Phoenix is built upon a language called <em>Elixir </em>while Node.js is built upon <em>JavaScript</em>.</p><p>I’ll go into more detail about the differences in a just a moment, however, I want to make it clear from the start that this book will be written for people already familiar with full-stack JavaScript development to transition to developing with Elixir/Phoenix (and not vice versa).</p><p>Another important thing to note is that this book is being written as I learn Elixir/Phoenix with no prior experience. Therefore, this book will be super practical. Reason being, when I have those “a-ha” moments where something clicks, I can explain to you exactly what made it click for me. I will also be using stories, analogies, and visual-friendly examples to reiterate what I am learning.</p><h3>Why Learn Phoenix?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVCY2dzmlGbxw-5Eog5ENA.png" /></figure><p>It’s very likely that you may not have heard of Phoenix. Unlike React, Redux, Vue.js, and other topics that I have covered, Phoenix has a lot less “buzz” surrounding it.</p><p>As you search through Medium, check your Twitter, and attend JavaScript meetups, you are not likely to have come across someone encouraging you to switch from Node.js and learn Phoenix. So, why learn Phoenix?</p><p>I’ll answer that question in two ways. First, I’ll let you be a fly on the wall of my developer journey so you can see why I find it beneficial. Then, I’ll give a more nerdy explanation and go over all the technical benefits in comparison to Node.js.</p><h4>Why I’m Leaning Phoenix</h4><p>I can’t stand the “fake it until you make it” and “form a very sharp opinion about why <em>x </em>is great and <em>y </em>sucks or you’re not a developer” mindsets that float around in the web development space. So, let me be very transparent for a refreshing break from all of that.</p><p>I’m currently unemployed and have been looking to build up my skills. The best way to learn skills has been to create content teaching others what I’m learning. I’ve already written about React, React VR, Redux, MongoDB, Firebase, and Node.js so I have covered all the fundamentals for full-stack React development. I’m in the position where I can now write about something more supplemental to those fundamentals.</p><p>I spent a lot of time going back and worth about what supplemental skill to learn and write about next. Here were some ideas I contemplated:</p><ul><li>GraphQL</li><li>React SVG animation</li><li>React Native</li><li>3D Modeling</li><li>Preact</li><li>TypeScript</li><li>Immutable.js</li></ul><p>All of the options above are still things I’d like to eventually learn, however, I started to ask myself: “What skill would give me the best bang for my buck?”</p><p>On top of that, I also have been noticing that a lot of the companies hiring for a React developer did not have a Node.js backend. Additionally, a developer that I had lunch with suggested I learn a secondary language.</p><p>So, I remembered a conversation with a developer friend who told me how Phoenix is super awesome. Phoenix is built on <em>Elixir</em> (a functional programming language), works really well with <em>PostgreSQL</em> (a SQL database unlike MongoDB), and contains a built-in streaming technology called <em>Channels.</em></p><p>Therefore, learning Phoenix definitely gave me the best bang for the buck and allows me to dive into more advanced topics of backend development.</p><h4>Why Phoenix is Technically Legit</h4><p>As previously mentioned, Phoenix is built off of Elixir and the Erlang VM. A couple things to note in regards to this.</p><ul><li>Elixir provides a stronger type system than JavaScript (Node.js) without needing preprocessing like with TypeScript.</li><li>Elixir is a <em>functional </em>programming language at its core and not merely a language that gives you the option to do functional stuff like JavaScript. Functional programming will be unpacked more in the next chapter. However, just know that we can <em>write less code</em> and have a better understanding of what our code does since it is also <em>declarative</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_ML5gW0hILWqO78Mr2-Lw.png" /><figcaption><a href="https://elixirschool.com/en/lessons/basics/enum/">Elixir School</a></figcaption></figure><ul><li>Elixir has performed incredibly well in comparison to Express (Node.js framework) and frameworks for other languages:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taApzgfd531EFvBXzKDs4w.png" /><figcaption><a href="https://gist.github.com/omnibs/e5e72b31e6bd25caf39a">Comparative Benchmark Numbers @ Rackspace</a></figcaption></figure><ul><li>Erlang VM (BEAM) has been developed on for over 25 years and the result is better stability and concurrency.</li></ul><p>Beyond that, I recommend checking out the <a href="http://www.phoenixframework.org/docs/overview">official site</a> and the <a href="https://www.amazon.com/Programming-Phoenix-Productive-Reliable-Fast-ebook/dp/B01FRIOYEC/ref=mt_kindle?_encoding=UTF8&amp;me=">sample chapter of <em>Programming Phoenix</em></a>.</p><p><strong>Fun Fact: </strong><a href="https://blog.discordapp.com/how-discord-handles-push-request-bursts-of-over-a-million-per-minute-with-elixirs-genstage-8f899f0221b4">Discord has been using Elixir to scale their applications</a>.</p><p>Whether the technical details mean anything to you or not, I’d still encourage you to learn how to build a Phoenix backend for React applications as you will learn a secondary programing language, functional programming skills, how to create a PostgreSQL database and API service, and other cool skills with backend development.</p><h3>Table of Contents</h3><ol><li><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Why Bother?</a></li><li><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Learning the Basics of Elixir</a></li><li><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-3-introduction-to-phoenix-9058de1ff5d4">Introduction to Phoenix</a></li><li><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-4-implementing-react-716979133669">Implementing a React frontend</a></li><li><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-5-working-with-postgresql-83ec4f3286b2">Working With PostgreSQL</a></li><li><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-6-creating-a-postgresql-api-service-9f2775161d3f">Building an API service for PostgreSQL</a></li><li><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-7-crud-operations-79d4e5af9a0d">CRUD Operations</a></li><li><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-8-user-authentication-fb1ff48a5e51">User Authentication</a></li><li><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-9-channels-245a24647e84">Channels</a></li><li><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-10-moving-forward-69303b6b75b0">Moving Forward</a></li></ol><h3>Chapter 2</h3><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-2-learning-the-basics-of-elixir-f9010fac8c59">Chapter 2 is now available.</a></p><h3>Sign Up for Notifications</h3><p><a href="http://codingartist.io/full-stack-react-phoenix/">Get notified when each chapter is released.</a></p><p>Cheers,<br>Mike Mangialardi<br>Founder of Coding Artist</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3c4a38846cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coding-artist/full-stack-react-with-phoenix-chapter-1-why-bother-d3c4a38846cf">Full-Stack React With Phoenix (Chapter 1 | Why Bother?)</a> was originally published in <a href="https://medium.com/coding-artist">Coding Artist</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>