<?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[Stories by Jennifer Snyder on Medium]]></title>
        <description><![CDATA[Stories by Jennifer Snyder on Medium]]></description>
        <link>https://medium.com/@jen.snyder?source=rss-5e3be1fbbd5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XucZ9xhyYc-3XUX3yo_9lQ.jpeg</url>
            <title>Stories by Jennifer Snyder on Medium</title>
            <link>https://medium.com/@jen.snyder?source=rss-5e3be1fbbd5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:12:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jen.snyder/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Use React to Display NASA’s Astronomy Picture of the Day — Part 3]]></title>
            <link>https://medium.com/@jen.snyder/how-to-use-react-to-display-nasas-astronomy-picture-of-the-day-part-3-fc636e2aefea?source=rss-5e3be1fbbd5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc636e2aefea</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jennifer Snyder]]></dc:creator>
            <pubDate>Thu, 11 Oct 2018 13:08:10 GMT</pubDate>
            <atom:updated>2018-10-11T13:08:10.376Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Use React to Display NASA’s Astronomy Picture of the Day — Part 3</h3><h4>Goal: Allow a user to click a button to view a random date’s photo</h4><p>After completing <a href="https://medium.com/@jlsnyder09/how-to-use-react-to-display-nasas-astronomy-picture-of-the-day-part-2-9b7612b72d">Part 2</a> of our project to display <a href="https://api.nasa.gov/api.html#apod">NASA’s Astronomy Picture of the Day</a>, we have an app that is working pretty well! When a user visits our page, they see today’s photo, and they can select a date from a calendar to show its associated picture. When I was first building this app and sharing it with my friends, I received a suggestion that a user might just want to view random photos and not have to select a day. So that’s what we’ll implement next!</p><p>The first thing we need to do is add a button. We’ll put the button in our DateInput component since it will be generating a random date.</p><pre><strong><em>//DateInput.js</em></strong><br>import React from &quot;react&quot;;<br>import DatePicker from &quot;react-datepicker&quot;;<br>import &quot;react-datepicker/dist/react-datepicker.css&quot;;</pre><pre>const DateInput = props =&gt; (<br>  &lt;div&gt;<br>    Select a Date:<br>    &lt;DatePicker<br>      selected={props.date}<br>      onChange={props.changeDate}<br>    /&gt;<br>  <strong>&lt;button&gt; Random photo&lt;/button&gt;</strong><br>&lt;/div&gt;<br>);</pre><pre>export default DateInput;</pre><p>We should see the button appear below our DatePicker input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*YCFxt3_aNgistC7L5Muh1g.png" /></figure><p>Next, we need to think about what we want to happen when we click our “Random photo” button. We want the button to return a random date, display the date in our DatePicker, make a fetch to the API using that date, and finally display the photo.</p><p>To make this happen, we need the state in our App component to change. That means that we need a function in App to handle the click, which we can pass down as a prop to our DateInput. For now, let’s just console.log “clicked” so we know it’s working.</p><pre><strong><em>//App.js</em></strong><br>import React, { Component } from &quot;react&quot;;<br>import moment from &quot;moment&quot;;</pre><pre>import DateInput from &quot;./components/DateInput&quot;;<br>import Photo from &quot;./components/Photo.js&quot;;</pre><pre>class App extends Component {<br>  state = {<br>    date: moment(),<br>    photo: &quot;&quot;<br>  };</pre><pre>formatDate = moment =&gt; {<br>    let year = moment.year();<br>    let month = moment.month() + 1;<br>    let day = moment.date();<br>    return `${year}-${month}-${day}`;<br>  };</pre><pre>changeDate = dateFromInput =&gt; {<br>    this.setState({ date: dateFromInput });<br>    this.getPhoto(this.formatDate(dateFromInput));<br>  };</pre><pre>componentDidMount() {<br>    fetch(`<a href="https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY`">https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY`</a>)<br>      .then(response =&gt; response.json())<br>      .then(json =&gt; this.setState({ photo: json }));<br>  }</pre><pre>getPhoto = date =&gt; {<br>    fetch(`<a href="https://api.nasa.gov/planetary/apod?date=${date}&amp;api_key=DEMO_KEY`">https://api.nasa.gov/planetary/apod?date=${date}&amp;api_key=DEMO_KEY`</a>)<br>      .then(response =&gt; response.json())<br>      .then(photoData =&gt; this.setState({ photo: photoData }));<br>  };</pre><pre><strong>handleClick = () =&gt; {<br>    console.log(&quot;clicked&quot;);<br>  };</strong></pre><pre>render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;NASA&#39;s Astronomy Picture of the Day&lt;/h1&gt;<br>        &lt;DateInput<br>          changeDate={this.changeDate}<br>          date={this.state.date}<br>          <strong>handleClick={this.handleClick}</strong><br>        /&gt;<br>        &lt;Photo photo={this.state.photo} /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br>export default App;</pre><p>Let’s click our “random photo” button. Hmm, nothing happens. What did we forget? We need to actually tell the button to call this function when it’s clicked! For that we need to use onClick.</p><pre><strong><em>//DateInput.js</em></strong></pre><pre>const DateInput = props =&gt; (&lt;div&gt;<br>    Select a Date:<br>    &lt;DatePicker selected={props.date} onChange={props.changeDate} /&gt;<br>    &lt;button <strong>onClick={props.handleClick}</strong>&gt;Random photo&lt;/button&gt;<br>  &lt;/div&gt;<br>)</pre><p>Now, when we click the button, we should see “clicked” in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*452ZK3VF79Q69BDN6EFyaQ.png" /></figure><p>Cool! So what do we actually want to happen? First, we need to get a random date. We are already using Moment.js for our dates, so it would be nice if we could find a way to generate a random Moment object. A quick google search led me to another package: <a href="https://www.npmjs.com/package/moment-random">moment-random</a>.</p><p>The first step is to install it:</p><pre>npm install --save moment-random</pre><p>Then, we need to import it to the file in which we will use it, which in our case is App.</p><pre><strong><em>//App.js</em></strong><br><strong>import momentRandom from &quot;moment-random&quot;;</strong></pre><p>To generate a random Moment.js object, we can call MomentRandom(). We can also specify an interval by passing in an end date and a start date: MomentRandom(end, start).</p><p>We need our random date to be included in the NASA Astronomy Picture of the Day API , which has photos for June 16, 1995 though today. Since we want the end date to be today, we can pass in moment(), which we know returns the current date. By looking at the Moment.js docs, we can see that there is a <a href="https://momentjs.com/docs/#/parsing/string-format/">“String + Format” method</a> to create a moment object with a specific date. We just need to call moment() with a date string followed by a string indicating the format of our date. For our date, that can look like this: moment(&quot;06-16-1995&quot;, &quot;MM-DD-YYYY&quot;). Putting this all together, we can get a random date by calling MomentRandom(moment(), moment(&quot;06-16-1995&quot;, &quot;MM-DD-YYYY&quot;).</p><p>What do we want to do with this random date? We want to set the state in our App ! So here’s what our handleClick function should look like:</p><pre>//App.js</pre><pre>class App extends Component {</pre><pre>...</pre><pre>handleClick = () =&gt; {<br>   <strong> let randomDate = momentRandom(moment(), moment(&quot;06-16-1995&quot;, &quot;MM-DD-YYYY&quot;));<br>    this.setState({ date: randomDate });</strong><br>  };</pre><pre>...</pre><pre>}</pre><p>Now check out what happens when we click the “Random photo” button!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*LBfezwGyRxNMo1v7g3bptg.png" /></figure><p>We get a random date in our DatePicker!</p><p>Our last step is to fetch the corresponding photo for this date. We’ve done this before! We know that we first need to format our Moment.js date into the date string we need for the API, which we will do by calling our formatDate function. Then, we will pass the formatted date into our getPhoto function to fetch the photo from the API. This function will update our state and display the correct photo. So, here’s the final version of our handleClick function.</p><pre>class App extends Component {</pre><pre>...</pre><pre>handleClick = () =&gt; {<br>   <strong> </strong>let randomDate = momentRandom(moment(), moment(&quot;06-16-1995&quot;, &quot;MM-DD-YYYY&quot;));<br>    this.setState({ date: randomDate });<br>    <strong>this.getPhoto(this.formatDate(randomDate))</strong><br>};</pre><pre>...</pre><pre>}</pre><p>And now when we click the “Random Photo” button, we see the photo for the random date!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBQ4VnE5HP-icgsnTHqXqw.png" /></figure><p>Awesome! I really like this feature! It makes me think about other features I’d like to add — wouldn’t it be cool to save your favorite photos? Aren’t some of the photos a little big? Could some styling help? Any other ideas? Maybe we’ll tackle some of these ideas in a future post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc636e2aefea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use React to Display NASA’s Astronomy Picture of the Day— Part 2]]></title>
            <link>https://medium.com/@jen.snyder/how-to-use-react-to-display-nasas-astronomy-picture-of-the-day-part-2-9b7612b72d?source=rss-5e3be1fbbd5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b7612b72d</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jennifer Snyder]]></dc:creator>
            <pubDate>Thu, 27 Sep 2018 13:13:32 GMT</pubDate>
            <atom:updated>2018-10-11T13:09:45.523Z</atom:updated>
            <content:encoded><![CDATA[<h4>Goal: Allow the user to select a date from a calendar to view the corresponding photo</h4><p>In <a href="https://medium.com/@jlsnyder09/how-to-use-react-to-display-nasas-astronomy-picture-of-the-day-283c01ff9e31">Part 1</a> of building a simple React app to display <a href="https://api.nasa.gov/api.html#apod">NASA’s Astronomy Picture of the Day</a>, we were able to make a fetch to the NASA APOD API to display the photo for a date entered by a user. We had three components: an App that rendered both a DateInput that asks the user to input a date and a Photo component that displays the photo. In the state of our App, we kept the date and the photo so we could get and receive the necessary information from the children components. In the version we built in Part 1, we required a user to enter the date in the exact format required by the API. Not ideal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdvspKZP-WhcRGRNYvDC8Q.png" /></figure><p>In working to improve this user experience, my second iteration had a form with dropdown menus for users to select a month, day, and year, which would then be properly formatted into a string when the form was submitted. I got it to work, but after testing out the app, I realized that entering dates this way was kind of a pain. So I found a better way!</p><h4>Understanding React DatePicker</h4><p>I came across the <a href="https://www.npmjs.com/package/react-datepicker">React Date Picker</a> package that provides a “simple and reusable DatePicker component for React.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*WeV-g5GSKrOdfxKq__D-aw.png" /></figure><p>To use the DatePicker, we first need to install the package.</p><p>npm install react-datepicker --save</p><p>Datepicker requires Moment.js and PropTypes, so I installed them as well.</p><p>npm install moment --save</p><p>npm install prop-types --save</p><p>DatePicker is relatively easy to use. It is a React component that can display a selected date and respond to a change in the date with a function. As shown in its documentation, the simplest form of a DatePicker is:</p><pre><strong>&lt;</strong>DatePicker<br>  selected<strong>=</strong>{this.state.date} <br>  onChange<strong>=</strong>{this.handleChange}<br><strong>/&gt;</strong></pre><p>This format is of course assuming that the date is stored in the state of the component that renders the DatePicker and that the component has a function to handle the change. Depending on the structure of your app, these elements may come from somewhere else, like the component’s props.</p><h4>Adding React DatePicker</h4><p>In our Astronomy Picture of the Day app, we will be rendering the DatePicker in the DateInput component. The date is stored in the state in the App component, which is the parent of DateInput. This means that our DatePicker’s selected date and function to handle the change in the date will come from its props, passed down from App.</p><p>In <a href="https://medium.com/@jlsnyder09/how-to-use-react-to-display-nasas-astronomy-picture-of-the-day-283c01ff9e31">Part 1</a>, we already set up our App to render the DateInput component and pass down a changeDate function. Now, we’ll also need to pass down the date from App&#39;s state to display in the DatePicker.</p><pre><strong><em>//App.js<br></em></strong>import React, { Component } from &quot;react&quot;;</pre><pre>import DateInput from &quot;./components/DateInput&quot;;<br>import Photo from &quot;./components/Photo.js&quot;;</pre><pre>class App extends Component {<br>  state = {<br>    date: &quot;&quot;,<br>    photo: &quot;&quot;<br>  };</pre><pre>  changeDate = e =&gt; {<br>    e.preventDefault();<br>    dateFromInput= e.target[0].value<br>    this.setState({ date: dateFromInput });<br>  };</pre><pre>render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;NASA&#39;s Astronomy Picture of the Day&lt;/h1&gt;<br>        &lt;DateInput<br>          changeDate={this.changeDate}<br>          <strong>date={this.state.date}</strong><br>        /&gt;<br>        &lt;PhotoContainer date={this.state.date} /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br>export default App;</pre><p>We can use our <a href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en">React Developer Tools</a> to verify that the date is now being passed down to DateInput along the with changeDate function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXNRaGtRrJmoULQCCw3aAA.png" /></figure><p>We will need to make some changes to our changeDate function later to handle the new input, but first we need to get an idea of <em>what</em> input we’ll get from this DatePicker component.</p><p>In the DateInput component, we can now render the DatePicker component and set its selected date to the date that was passed down to DateInput. The DateInput component also receives a function from its parent to handle the change in the date — changeDate. We can set this to be called onChange of the DatePicker. In this component, I also had to require the CSS file from the DatePicker package:</p><pre><strong><em>//DateInput.js</em></strong><br>import React from &quot;react&quot;;<br><strong>import DatePicker from &quot;react-datepicker&quot;;<br>import &quot;react-datepicker/dist/react-datepicker.css&quot;;</strong></pre><pre>const DateInput = props =&gt; (<br>  <strong>&lt;div&gt;<br>    Select a Date:<br>    &lt;DatePicker<br>      selected={props.date}<br>      onChange={props.changeDate}</strong><br><strong>    /&gt;<br>  &lt;/div&gt;</strong><br>);</pre><pre>export default DateInput;</pre><p>Check out our page now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIleE7ek5vYOllB-3Z1ZvQ.png" /></figure><p>Cool! We can now select a date on a calendar!</p><p>But wait! You might have noticed some scary-looking warnings pop up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfvxyel_fBbTbnug-LY1Gw.png" /></figure><p>What’s going on?! It looks like our date is currently a string, but the DatePicker was expecting an object.</p><h4>Using Moment.js</h4><p>This is the tricky part about DatePicker — it uses Moment.js, which creates a wrapper for the JavaScript Date object. Let’s walk through how we’ll update the date in our app to use Moment.js.</p><p>In our app, we want to automatically load the photo for today when the page loads. To do this, we’ll set the date in App’s state to the current date. To get the current date using Moment.js, you can call moment() without any parameters. Remember to import moment or you’ll see an error telling you that ‘moment’ is not defined.</p><pre>import React, { Component } from &quot;react&quot;;<br><strong>import moment from &quot;moment&quot;;</strong></pre><pre>import DateInput from &quot;./components/DateInput&quot;;<br>import Photo from &quot;./components/Photo.js&quot;;</pre><pre>class App extends Component {<br>  state = {<br>    date: <strong>moment()</strong>,<br>    photo: &quot;&quot;<br>  };</pre><p>If we look at our app now, we can see that the date is filled in with today’s date! Pretty cool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JukJk4XUiWgkCLqeIeD18Q.png" /></figure><p>What happens if we try to change the date?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwFxGAhEfrC4CbrISBQMTw.png" /></figure><p>Well, that’s not great. But we can see that the error occurred in the changeDate function in App. So at least we know that the correct function is being called when we change the date.</p><p>According to the DatePicker documentation, the function that handles the change is passed the date as a Moment object. That means that we can store this date in state in App and get the photo using this date object.</p><pre>class App extends Component {<br> <br>...</pre><pre>  changeDate = <strong>dateFromInput</strong> =&gt; {<br>    this.setState({ date: dateFromInput });<br>    this.getPhoto(dateFromInput);<br>  };</pre><pre>...</pre><pre>}</pre><p>Now what happens when we change the date?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jF9JXlPvrjKxFe4kHOA2-Q.png" /></figure><p>Where’s the photo? If we check our React dev tools, we can see that the date has been updated to a Moment object, but our photo is not there. Instead, we have an error message telling us that our date is not formatted correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5SzgpokgrlolJ39uNLJdQ.png" /></figure><h4>Formatting the Date</h4><p>One more step to get our DatePicker working correctly. We need to format our Moment object into the date format the API needs : “YYYY-MM-DD”. How can we do this?</p><p>Moment objects have built-in functions that can help us get the pieces of the date that we need. Let’s take this one step at a time using the current date.</p><pre>let today = moment()</pre><p>We can easily get the year:</p><pre>today.get(&#39;year&#39;)<br><em>//2018</em></pre><p>The month is a little trickier.</p><pre>today.get(&#39;month&#39;)<br><em>//8</em></pre><p>Hmm. It’s September, so we would expect to get 9. Unfortunately, Moment numbers the months starting at 0, so we’ll have to remember to add 1 to get the number we need.</p><p>Finally, we can get the date:</p><pre>now.get(&#39;date&#39;)<br><em>//26</em></pre><p>Now we can write a function in App using these methods to format the moment into the string we need to make a fetch to the API: YYYY-MM-DD. After testing, I realized that the API also accepts months and days with only one digit, so we don’t need to worry about adding a 0 to single-digit numbers.</p><pre>class App extends Component {<br> ...</pre><pre><strong>  formatDate = moment =&gt; {<br>    let year = moment.year();<br>    let month = moment.month() + 1;<br>    let day = moment.date();<br>    return `${year}-${month}-${day}`;<br>    }</strong></pre><pre> ...<br>}</pre><p>Finally, we need to format the dateFromInput before we pass it to the getPhoto function.</p><pre>class App extends Component {</pre><pre>...</pre><pre>  changeDate = dateFromInput =&gt; {<br>    this.setState({ date: dateFromInput });<br>    this.getPhoto(<strong>this.formatDate(</strong>dateFromInput<strong>)</strong>);<br>  };</pre><pre>...</pre><pre>}</pre><p>Cool! It works!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPw_ggi_pudBSSiegJ6eWQ.png" /></figure><p>A user can now easily select a date from a calendar, and our app will render the appropriate Astronomy Picture of the Day! Awesome!</p><p>But I still think we have some room for improvement. How about making a button that will return a random photo and show the date it’s from? That would be neat! Check out how to implement this feature in <a href="https://medium.com/@jlsnyder09/how-to-use-react-to-display-nasas-astronomy-picture-of-the-day-part-3-fc636e2aefea">Part 3</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b7612b72d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use React to Display NASA’s Astronomy Picture of the Day]]></title>
            <link>https://medium.com/@jen.snyder/how-to-use-react-to-display-nasas-astronomy-picture-of-the-day-283c01ff9e31?source=rss-5e3be1fbbd5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/283c01ff9e31</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jennifer Snyder]]></dc:creator>
            <pubDate>Thu, 27 Sep 2018 02:33:13 GMT</pubDate>
            <atom:updated>2018-09-27T13:14:34.708Z</atom:updated>
            <content:encoded><![CDATA[<h4>Goal: Display NASA’s Astronomy Picture of the Day from the date a user inputs</h4><p>In my first week of learning <a href="https://reactjs.org/">React</a>, after wrapping my head around the ideas of state and props, I discovered that it’s really fun to build things with React! I wanted to build something of my own, so I decided to use <a href="https://api.nasa.gov/api.html#apod">NASA’s Astronomy Picture of the Day (APOD) API</a> to build an app that allows users to view photos based on a date. NASA claims that their Astronomy Picture of the Day website “has the popular appeal of a Justin Bieber video,” so I wanted to try to make something even better. We’ll walk through the steps to create a very simple React app that displays a photo from the NASA APOD API based on the date that a user inputs.</p><h4>Creating the App</h4><p>To create and start the app, you can use the handy <a href="https://github.com/facebook/create-react-app">Create React App</a> project generator developed by Facebook:</p><pre>create-react-app astronomy-picture-of-the-day<br>cd astronomy-picture-of-the-day<br>npm start</pre><p>This sets up a React app so you can start building! In your browser, you should automatically be redirected to <a href="http://localhost:3000/">localhost:3000</a> and see the “Welcome to React” page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*1s1SKNnA18w7C_V7BicClw.png" /></figure><p>This page even tells us where to get started: src/App.js.</p><h4>Setting Up The Components</h4><p>Our App is going to render two components: DateInput to get the user’s input of a date and Photo to display the photo. Create a folder in the src folder called components and then create a file for each of these components in this folder:</p><pre>cd src<br>mkdir components<br>cd components<br>touch DateInput.js<br>touch Photo.js</pre><p>I like to first set up a very simple static version of my app to ensure that I have the correct import and export in each file.</p><pre><strong><em>//App.js<br></em></strong>import React, { Component } from &quot;react&quot;;<br>import DateInput from &quot;./components/DateInput&quot;;<br>import Photo from &quot;./components/Photo.js&quot;;</pre><pre>class App extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;NASA&#39;s Astronomy Picture of the Day&lt;/h1&gt;<br>        &lt;DateInput /&gt;<br>        &lt;Photo /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br>export default App;</pre><pre><strong><em>//DateInput.js<br></em></strong>import React from &quot;react&quot;;</pre><pre>const DateInput = props =&gt; &lt;div&gt;DateInput&lt;/div&gt;;</pre><pre>export default DateInput;</pre><pre><strong><em>//Photo.js<br></em></strong>import React from &quot;react&quot;;</pre><pre>const Photo = props =&gt; &lt;div&gt;Photo&lt;/div&gt;;</pre><pre>export default Photo;</pre><p>In the browser, you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*Zpl9ySQlCUVqr29XqSmEhw.png" /></figure><p>Cool! Our components are rendering correctly.</p><h4>Thinking About State</h4><p>Next, we want to think about what state we need and where it should live. We know that the DateInput component will receive a user’s input of a specific date. We will use that date to fetch a picture from NASA’s Astronomy Picture of the Day API, then display that picture in the Photo component. Both the date and the photo can change, so we’ll keep both of them in state.</p><p>Where should the state live? The DateInput component will update the date, which will be used to fetch and update the photo, which will need to be passed to the Photo component to render. Because of this, we will keep the date and photo in the common parent to these components, which is App. For now, we’ll add state to our App and initialize each piece with an empty string.</p><pre>class App extends Component {<br>  <strong>state = {<br>    date: &quot;&quot;,<br>    photo: &quot;&quot;<br>  };</strong><br>   <br> ...</pre><pre>}</pre><p>Using the <a href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en">React Developer Tools</a>, we can verify that our state is where it should be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*JA_cAZ2_aVh9LPrDls2aqA.png" /></figure><h4>Getting a Date</h4><p>Now that we have the basic parts of our React app set up, we can think about the data flow in our app. From a user’s perspective, they will enter a date and the corresponding photo will appear. In terms of our app, that means the following steps will occur:</p><ol><li>The user will input a date in the DateInput component</li><li>The App’s state will update to reflect the user’s date input</li><li>We will use the date to make a fetch to the API, then update the photo in the App&#39;s state</li><li>The Photo component will display the photo</li></ol><p>Let’s focus on the first two steps for now. We need to have a form in DateInput where a user can input a date. When the user submits this form, it needs to update the date in the state of App. That means we need to write a function in App to update the state, and then pass that function down as a prop to DateInput. The function will be called when the form is submitted, and update the state in App using the value entered into the form. Since we haven’t created the form yet, let’s just prevent the default behavior of the event (so the page doesn’t refresh) and log the event’s target. This will help us determine how to get the value the user entered.</p><pre>class App extends Component {<br> <br>...</pre><pre><strong>changeDate = e =&gt; {<br>    e.preventDefault();<br>    console.log(e.target);<br>  };</strong></pre><pre>render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;NASA&#39;s Astronomy Picture of the Day&lt;/h1&gt;<br>        &lt;DateInput <strong>changeDate={this.changeDate}</strong> /&gt;<br>        &lt;Photo /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>We can verify that the function has been passed to our DateInput component by using the React dev tools:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGRKlw5XuhmWo9uiXRiSDg.png" /></figure><p>Now we need a form in DateInput. When a user submits this form, it will call on the changeDate function that is in its props. For now, let’s assume the user will input the date in a very specific format: YYYY-MM-DD (the reason for this will become apparent in our next step; we’ll improve the user experience later!)</p><pre>const DateInput = props =&gt; <strong>(<br>  &lt;form onSubmit={props.changeDate}&gt;<br>    Enter a date (YYYY-MM-DD):<br>    &lt;input /&gt;<br>    &lt;input type=&quot;submit&quot; /&gt;<br>  &lt;/form&gt;<br>);</strong></pre><p>We should now see a form where “DateInput” used to be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*xp5zftuGwH5YSCnFzVOeFQ.png" /></figure><p>Let’s enter a date and see what happens. In our console, we should see the event’s target:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mg2m1DBpsUH3cyQh7aZKw.png" /></figure><p>This shows us that the event target is the form. The first input field in the form is where the user enters the date, so we can access the value of that input using e.target[0].value. In our changeDate function, we want to update the date in our App’s state to this value.</p><pre>class App extends Component {<br> <br>...</pre><pre>changeDate = e =&gt; {<br>    e.preventDefault();<br>    <strong>let dateFromInput = e.target[0].value;</strong><br>    <strong>this.setState({ date: dateFromInput });<br> </strong> };</pre><pre>...</pre><pre>}</pre><p>Now when we enter a date and click Submit, we should see the state updated with the date we entered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8sftgdFUQAPKBYimfZLtw.png" /></figure><p>Now we’re ready to get a photo!</p><h4>Fetching Today’s Photo</h4><p>The NASA APOD API is pretty simple to use. NASA provides a default API key, but if (like me), you exceed the rate limit and can no longer make requests, you can sign up to immediately <a href="https://api.nasa.gov/index.html#apply-for-an-api-key">get your own API key</a>. The query has one optional parameter of date, which defaults to today’s date, and needs to be formatted YYYY-MM-DD (just like our state!).</p><p><a href="https://api.nasa.gov/planetary/apod?date=2009-12-19&amp;api_key=DEMO_KEY">https://api.nasa.gov/planetary/apod?date=2018-03-14&amp;api_key=DEMO_KEY</a></p><p>Where are we going to make this fetch? We want to store the photo in the state of the App, so we’ll do it there!</p><p>It would be nice if today’s photo automatically appeared when a user visits the page, before the user even enters a date. Luckily, React has a lifecycle method that we can use to make a fetch just before the component renders: componentDidMount. If we make a fetch to the API without providing a date, it will return today’s photo. (If you are using your own API key, you should replace DEMO_KEY in the url below.)</p><pre>class App extends Component { <br>  ...</pre><pre>  <strong>componentDidMount() {<br>    fetch(`</strong><a href="https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`"><strong>https://api.nasa.gov/planetary/apod?api_key=$DEMO_KEY`</strong></a><strong>)<br>      .then(response =&gt; response.json())<br>      .then(json =&gt; this.setState({ photo: json }));<br>  }</strong></pre><pre>  ...<br>}</pre><p>We can use the React dev tools to see that we now have today’s photo in the state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfqNTNaIPFLDn5IWtSElRg.png" /></figure><p>Cool! Let’s see if we can display it. We need to first pass this photo down to the Photo component, which will render it.</p><pre>class App extends Component {<br> <br>  ...</pre><pre>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;NASA&#39;s Astronomy Picture of the Day&lt;/h1&gt;<br>        &lt;DateInput changeDate={this.changeDate} /&gt;<br>        &lt;Photo <strong>photo={this.state.photo}</strong> /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>Now we just need to update our Photo component to display the photo that it has access to in its props. We’ll show the picture’s title, the photo from the url, and the explanation.</p><pre>const Photo = props =&gt; (<br>  &lt;div&gt;<br>    <strong>&lt;h3&gt;{props.photo.title}&lt;/h3&gt;<br>    &lt;img src={props.photo.url} alt={props.photo.title} /&gt;<br>    &lt;p&gt;{props.photo.explanation}&lt;/p&gt;</strong><br>  &lt;/div&gt;<br>);</pre><p>If we look in the browser, we should see today’s photo!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSR4d7tzfz8cEGq0Ywd7SA.png" /></figure><h4>Changing the Picture Based On Date</h4><p>Our last step is to use the date a user inputs to fetch a photo to display.</p><p>We need to write a function that will take in an argument of a date, make a fetch to the url with the date given, and set the photo in the state to the photo data received from the API.</p><pre>class App extends Component { <br> ...</pre><pre><strong> getPhoto = date =&gt; {<br>    fetch(`</strong><a href="https://api.nasa.gov/planetary/apod?date=${date}&amp;api_key=DEMO_KEY`"><strong>https://api.nasa.gov/planetary/apod?date=${date}&amp;api_key=DEMO_KEY`</strong></a><strong>)<br>      .then(response =&gt; response.json())<br>      .then(photoData =&gt; this.setState({ photo: photoData }));<br>  };</strong></pre><pre>...</pre><pre>}</pre><p>When do we we want to invoke this function? After a user inputs a date and clicks submit. We already have a function that handles that — changeDate! We can call getPhoto at the same time that we set the date in state to fetch the corresponding photo.</p><pre>class App extends Component {</pre><pre>...</pre><pre>changeDate = e =&gt; {<br>    e.preventDefault();<br>    let dateFromInput = e.target[0].value;<br>    this.setState({ date: dateFromInput });<br>    <strong>this.getPhoto(dateFromInput);</strong><br>  };</pre><pre>}</pre><p>We can make sure all of this is working by entering a date and clicking submit. The photo changes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3sP8W8FXfgsqEkH5siSlg.png" /></figure><p>Now, when you enter a date (currently only in the correct format), you should see the title, photo, and description for the Astronomy Picture of the Day!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdvspKZP-WhcRGRNYvDC8Q.png" /></figure><p>Awesome! We made a super simple React app!</p><p>Next, we’ll greatly improve the user experience by allowing them to select a date on a calendar. Check out <a href="https://medium.com/@jlsnyder09/how-to-use-react-to-display-nasas-astronomy-picture-of-the-day-part-2-9b7612b72d">Part 2</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=283c01ff9e31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This Post belongs_to Me]]></title>
            <link>https://medium.com/@jen.snyder/this-post-belongs-to-me-b4c52ad94d8f?source=rss-5e3be1fbbd5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4c52ad94d8f</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Jennifer Snyder]]></dc:creator>
            <pubDate>Thu, 13 Sep 2018 13:08:11 GMT</pubDate>
            <atom:updated>2020-02-20T14:51:39.546Z</atom:updated>
            <content:encoded><![CDATA[<p>Active Record Associations seem pretty simple. A blog belongs to an author. A blog has many posts. A post has many comments. A blog has many comments through posts. Put a few words into your models, and the magic of Active Record takes care of the rest.</p><p>But there is one relationship that seems to behave in a few slightly weird ways that have tripped me up: belongs_to. What seems like a very straightforward relationship actually has a few strange rules that can cause annoying bugs. I found these while working on a project with a partner to create a Game of Thrones Character Tracker. We designed this to help a user keep track of all the characters on the TV show as they watch it, since we know that there are a whole lot of white men with beards to get confused about.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F106XY1lj3eKfqE%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fgame-of-thrones-what-confused-106XY1lj3eKfqE&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F106XY1lj3eKfqE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/401de0c10c4038768f86c171ce39ae49/href">https://medium.com/media/401de0c10c4038768f86c171ce39ae49/href</a></iframe><p>In our project, we had a Character model and a House model. A house has_many characters. A character belongs_to a House. Seems simple enough. But some strange things started happening.</p><p>We seeded our database with information from a <a href="https://api.got.show/doc/">Game of Thrones API</a>, which provided everything that we needed to create our houses and characters. We created House objects for all of the houses in the series with no problem. We thought we had created Character objects for all of the characters (apparently there are 2028 of them), but when we checked in the Rails console, we had no characters. We also couldn’t create any new characters. We had no idea what was going on.</p><p>A couple of pain-staking hours later, we finally discovered the problem. It was all because of belongs_to. When you create a belongs_to association, the default behavior is to require that relationship. So, in our case, a character <strong>has to</strong> belong to a house. It turns out, in the 2028 characters we got from the Game of Thrones API, some of them did not have a house assigned to them. And that meant that none of our characters were created. It was an easy fix once we found the problem. We just had to add optional: true to our belongs_to relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*jlqRksTDNhJ28OLUMTFtPw.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ffmd46gcrNQJePMU6xa%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fgameofthrones-arya-bows-well-done-fmd46gcrNQJePMU6xa&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Ffmd46gcrNQJePMU6xa%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/d33bb3f650ea30683997922d23529ba9/href">https://medium.com/media/d33bb3f650ea30683997922d23529ba9/href</a></iframe><p>The next problem came later, when we had added another belongs_to relationship. We wanted users to be able to track the location of characters as the show progresses, so they could see where characters were and which characters were in certain locations. We created our locations, and added in the belongs_to relationship. We even remembered to include optional: true!</p><p>When a user added a character to track, we wanted them to be able to either choose an existing location or create a new location, so we built a nested form.Inside of our character form, we created a dropdown menu of existing locations by using collection_select, and used fields_for to create a nested form to create a new location.</p><p>Choose an existing location<br> &lt;%= f.label :location_id %&gt;<br> &lt;%= f.collection_select :location_id, Location.all, :id, :name, include_blank: ‘Unknown’ %&gt;<br> or create a new location:<br> &lt;%= f.fields_for <a href="http://twitter.com/user_character">@</a>location do |l|%&gt;<br> Name &lt;%= l.text_field :name %&gt;<br> Description &lt;%= l.text_field :description %&gt;<br> &lt;% end %&gt;</p><p>The dropdown menu worked perfectly, but the nested form for location didn’t show up!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lT8Bnmsj6ZbQlwIlpsedRg.png" /></figure><p>What was going on?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fj6Q00U29sHyzS%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fconfused-direwolf-j6Q00U29sHyzS&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fj6Q00U29sHyzS%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/40f6205fcd59346c3d037aebe43a92bf/href">https://medium.com/media/40f6205fcd59346c3d037aebe43a92bf/href</a></iframe><p>I knew that I had to create a new Location object, so I tried @character.location.build to create a new location object associated with the character. It didn’t work. Guess what? Another weird belongs_to rule! For belongs_to, the syntax to create a new associated object is different from the other types of Active Record associations. To create a new location for a character, which belongs to a location, I had to use @character.build_location. Weird, but it worked!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*MO9b4lVIeGha8aZ03T7bLw.png" /></figure><p>So, belongs_to can cause some headaches if you are not careful about following its slightly strange rules.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl4FGEN5TGVbouswtW%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fprepareforwinter-l4FGEN5TGVbouswtW&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl4FGEN5TGVbouswtW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/539c4b6b556162502dd24ead7f2124ed/href">https://medium.com/media/539c4b6b556162502dd24ead7f2124ed/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4c52ad94d8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Enums to Make Everything Better]]></title>
            <link>https://medium.com/@jen.snyder/using-enums-to-make-everything-better-21fa19d6bc3e?source=rss-5e3be1fbbd5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/21fa19d6bc3e</guid>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Jennifer Snyder]]></dc:creator>
            <pubDate>Thu, 16 Aug 2018 13:05:55 GMT</pubDate>
            <atom:updated>2018-08-16T19:43:15.554Z</atom:updated>
            <content:encoded><![CDATA[<h4>Okay, maybe not everything. But definitely some of the things.</h4><p>When I log in to Netflix, after scrolling past the auto-playing trailer of a Netflix original movie that I don’t want to watch right now (though I probably will eventually — I do recommend <a href="https://www.buzzfeed.com/jennaguillaume/set-it-up-netflix-review?utm_term=.xglmmbA6xp#.kwQee03q98">Set It Up</a> for your rom-com needs), I’m greeted with never-ending rows of options. I could scroll through what’s popular on Netflix or “Trending Now,” find something new in one of the genres Netflix recommends for me (thank you, I do enjoy “TV Shows Featuring a Strong Female Lead”), or, most likely, continue watching a TV show that I’m currently binging. But how does Netflix know that I’ve already finished the new season of <em>Orange Is The New Black</em>? Or that I’m currently on Season 3, Episode 7 of <em>The Office, </em>even through I’ve watched the entire series at least a dozen times? What information does Netflix store that sorts these shows appropriately, and how embarrassed by this data should I be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcZMLYZISSeyCBSCaUiNaQ.png" /><figcaption>Really, the main reason I keep my Netflix subscription.</figcaption></figure><p>I can imagine how Netflix might store this type of data. Let’s say we have a table that stores all of the TV shows on Netflix. We want to have some way of telling what the status of each TV show for the user is: are they currently watching it, have they finished watching it, or have they never watched any of it? So, on our tv_shows table, along with the title of the show, we could have a status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*bwevC5ldkygxrhjJv1m6cw.png" /></figure><p>This would store a different string as the status for each TV show. To find all of the shows that I have watched, I would look for all of the shows where the status is “watched”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8S5VcXucOr3JIpZrbm9-ow.png" /></figure><p>This is do-able, and I could write methods to return the shows I want, but typing in a string for the status for every single TV show is just asking for typos in your data, and is definitely not DRY, fast, or easy to work with.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5wWf7GR2nhgamhRnEuA%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Feditingandlayout-the-office-true-dwight-5wWf7GR2nhgamhRnEuA&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2F5wWf7GR2nhgamhRnEuA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/782a13fddf49d76e578bb659939ff401/href">https://medium.com/media/782a13fddf49d76e578bb659939ff401/href</a></iframe><p>So using strings to store this information is probably not the best option. Instead, we could store those three statuses on a separate statuses table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*3Mwd8_R-U9xyftGim95t0w.png" /></figure><p>Then, on our tv_shows table, we could use a foreign key called status_id to identify the status of each show:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*JyAwyRhiY-EszEPU13-ULA.png" /></figure><p>Using the information on these two tables, I would be able to appropriately sort the TV shows. I could create a row of shows to “Continue Watching” by selecting all of the shows that have a status_id of 3, and another row called “Watch Again” by selecting those with a status_id of 2. To do this, I would probably want to write class methods for the TvShow model, such as this .watched_shows method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*NqHsvepgsUulg-jIhPRvTg.png" /><figcaption>A method to find all of the TV shows with a “watched” status. This will probably return a lot of shows.</figcaption></figure><p>I could then call TvShow.watched_shows and receive a list of all the shows that I have watched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0qtXyof8vu-tOaWOQNYGg.png" /></figure><p>I could create similar methods for “shows in progress” and “unwatched shows.” That seems like a lot of work.</p><p>In addition, let’s say I wanted to find out the status of <em>Parks and Recreation</em>. I can find the TV Show by its title, then return its status_id:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhuEasVLDnb-pDxt9ZBMpw.png" /></figure><p>2? What does that mean? In order to actually tell what the status of <em>Parks and Recreation</em> is, I would then need to find what a status_id of 2 means using the statuses table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j26YGfXdqoNnWUQqCkOgEA.png" /></figure><p>But this returns a status object. If I just want the string “watched,” I have one more step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCCsvyIiQQbtBC6qdOiRZg.png" /></figure><p>And now I finally know that I’ve watched <em>Parks and Rec</em>.</p><p>I could make this slightly easier by creating an association between the two classes, where a status has_many TV shows and a show belongs_to a status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*7VRS9fRfbQ9vgDk48zlqAQ.png" /></figure><p>Then, I could find the status of a show by calling status on it to get the status object, then status again to get the string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GcmujCC47NCTfwbX3TfvuQ.png" /></figure><p>This improves it a little, but it all seems very messy and confusing. We still need to write additional methods to sort the data, and it doesn’t really make sense to have an entire table to store the name of the three statuses.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F4cuyucPeVWbNS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Freddit-october-brotherinlaw-4cuyucPeVWbNS&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F4cuyucPeVWbNS%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="311" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5b09f0c79425d2d57ab75c6e4f6a593/href">https://medium.com/media/d5b09f0c79425d2d57ab75c6e4f6a593/href</a></iframe><p>Enums can make this better! They can help our data become more readable and easier to work with. Instead of a TV show having a foreign key of status_id , we can use an enum to store the name of the status directly on the tv_shows table, without using a string or compromising any of the functionality that we need.</p><p>An enum can be used when there are only a few possible values for an attribute. In this case, our status can only be “watched,” “not watched,” or “in progress.” We can create an enum for the status of a TV show, which we can store on our tv_shows table, meaning we no longer need the statuses table. The statuses will still be stored as integers, but we can use the actual name of each status to find the shows we are after. Cool, right?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5wWf7H89PisM6An8UAU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Feditingandlayout-the-office-michael-scott-5wWf7H89PisM6An8UAU&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2F5wWf7H89PisM6An8UAU%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/668b2a422ef429e160bb59de8b08eafa/href">https://medium.com/media/668b2a422ef429e160bb59de8b08eafa/href</a></iframe><p>Here’s how this works. First, we create the tv_shows table with columns for a title stored as a string and a status stored as an integer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*lTxdaMZtpwxjHbNIPc-ciw.png" /><figcaption>Migration to create the tv_shows table. Notice that status is an integer.</figcaption></figure><p>Next, we define the possible values for the status enum in the TvShow model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*PI3AeRMX0ARxq-Uyh_c17Q.png" /></figure><p>The order here <strong>does </strong>matter. Each status is now associated with an integer, starting with 0, which you can see by calling TvShow.statuses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*4CJvTD7G5SUOGldyiQr3fA.png" /></figure><p>When we look at our tv_shows table now, we can see that the status is actually stored as an integer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*cmXxLoSp-BXC06_SVOeKRQ.png" /></figure><p>This set-up gives us all of the functionality that we need, without having to write any new methods!</p><p>To find all of the shows that I have watched, we now only need to call TvShow.watched:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceP0BQIAPkeUzJgf0nVC6Q.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oEjHYibHwRL7mrNyo%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fthe-office-nice-pam-3oEjHYibHwRL7mrNyo&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3oEjHYibHwRL7mrNyo%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="219" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cff890874b202031574686073f88be3/href">https://medium.com/media/1cff890874b202031574686073f88be3/href</a></iframe><p>Woah! I didn’t have to do anything else, and it returned all of the shows with a status of “watched.” We can also see that the SQL used to retrieve these shows from our database used the integer 1 as the status. So enums are basically acting as both strings and integers at the same time. This means that we can use them in all of the ways that we used the foreign id in our previous set-up, but with simple, readable methods based on the name of each status.</p><p>Maybe I want to find out the status of <em>The Office</em>. That’s easy enough. I can find the TV show by its title, then return its status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTwQDl9LfImUcE4Kb5b20Q.png" /></figure><p>Using enums means that I now receive a string as the status, so I can easily see that <em>The Office </em>is in_progress.</p><p>But that’s not all! Enums give you a bunch of other built-in methods, without you having to do anything else.</p><p>Have I watched <em>Bojack Horseman</em>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Qu40ksyfTOjpMgaDDTGYQ.png" /></figure><p>Sure have! Look at that again. I called <em>.watched? </em>on the TvShow object, and it returned true . I didn’t have to write a method anywhere. The enum did it!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5wWf7GW1AzV6pF3MaVW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Feditingandlayout-the-office-high-five-5wWf7GW1AzV6pF3MaVW&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2F5wWf7GW1AzV6pF3MaVW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="251" frameborder="0" scrolling="no"><a href="https://medium.com/media/4390e4ee60076108b0ace6cdc4f429c6/href">https://medium.com/media/4390e4ee60076108b0ace6cdc4f429c6/href</a></iframe><p>What if I start watching <em>Stranger Things</em>? Do I have to remember the integer “in progress” is associated with to change its status? Of course not! I just need to find the show and set its status to “in_progress”. Then, I can save the change to the database, where it will update the integer in the status column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9mqt8c7cDaezBwNqbxYXQ.png" /></figure><p>Even easier, I can use a bang method to change the status. Let’s say I finally finish watching all of the episodes of <em>Black Mirror</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HVBakcSszSjgVkRUkNQbA.png" /></figure><p>This automatically updates the status for the show in the tv_shows table, as you can see by the UPDATE SQL. Pretty cool!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FIs1O1TWV0LEJi%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fexcited-the-office-celebrate-Is1O1TWV0LEJi&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FIs1O1TWV0LEJi%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/d870c8276e8c4b2b1048d97baec1c4e5/href">https://medium.com/media/d870c8276e8c4b2b1048d97baec1c4e5/href</a></iframe><p>These methods can of course be used in conjunction with your other favorite methods, too. To find out how many shows I am currently watching, I could call TvShow.in_progress.count:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w0IRD5m9FU1qoFl7jpvdMg.png" /></figure><p>Looks like I’m currently watching 3 TV shows. Enums definitely seem like the best way to represent this data, providing me with simple, readable methods that I can quickly use to find the information I need. As I continue to learn and use enums, I’m sure I will discover even more benefits and interesting ways to use them.</p><p>But for now, back to Netflix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*ocQvFXaxx4hiXw567JCWlA.png" /></figure><p>Shout out to Justin Weiss, whose post about enums helped me tremendously: <a href="https://www.justinweiss.com/articles/creating-easy-readable-attributes-with-activerecord-enums/">https://www.justinweiss.com/articles/creating-easy-readable-attributes-with-activerecord-enums/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21fa19d6bc3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aren’t hashes the coolest?]]></title>
            <link>https://medium.com/@jen.snyder/arent-hashes-the-coolest-1fb8bdb280?source=rss-5e3be1fbbd5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fb8bdb280</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Jennifer Snyder]]></dc:creator>
            <pubDate>Thu, 02 Aug 2018 12:36:58 GMT</pubDate>
            <atom:updated>2018-08-02T12:36:58.626Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started learning to code a few months ago, I immediately loved the structure and logic it provided, how it made sense and worked how I expected it to. I remember reading that Yukihiro “Matz” Matsumoto created Ruby to “make programmers happy” and wondering how on Earth a language was capable of doing that. Now that I’ve had a little more experience with Ruby, I can see what he meant. A language that has a limited number of key words can create such complex relationships and do so many interesting things. Learning about the data structures that exist in programming satisfies my need for organization and logic, but I think the first time I really appreciated how cool code can be was when I started working with hashes.</p><p>A hash is relatively simple in its basic form. You have some curly braces filled with keys pointing to their corresponding values with a hash-rocket. (Side note: how can you not love something that’s called a hash-rocket?)</p><pre>{key1 =&gt; value1, key2 =&gt; value2, key3 =&gt; value3}</pre><p>Or, you can forgo the hash-rocket syntax (as fun as it is) and form your key-value pairs using symbols.</p><pre>{key1: value1, key2: value2, key3: value3}</pre><p>Either way, it’s easy to see how your data is related. However, from this simple form, it’s possible to create complex relationships and store information in a way that makes working through problems much easier. Here are some of the experiences I’ve had with hashes that made me genuinely think “woah, that’s really cool.”</p><h3><strong>Iterating through nested hashes is crazy.</strong></h3><p>One of the first times I realized just how complex relationships between pieces of data in a hash could be, and how a hash could be manipulated to take different shapes, was when I was working on a lab in the Flatiron pre-work called “Pigeon Organizer.” In the lab, I started with a nested hash containing data about some pigeons:</p><pre>pigeon_data = {<br>  :color =&gt; {<br>    :purple =&gt; [&quot;Theo&quot;, &quot;Peter Jr.&quot;, &quot;Lucky&quot;],<br>    :grey =&gt; [&quot;Theo&quot;, &quot;Peter Jr.&quot;, &quot;Ms. K&quot;],<br>    :white =&gt; [&quot;Queenie&quot;, &quot;Andrew&quot;, &quot;Ms. K&quot;, &quot;Alex&quot;],<br>    :brown =&gt; [&quot;Queenie&quot;, &quot;Alex&quot;]<br>  },<br>  :gender =&gt; {<br>    :male =&gt; [&quot;Alex&quot;, &quot;Theo&quot;, &quot;Peter Jr.&quot;, &quot;Andrew&quot;, &quot;Lucky&quot;],<br>    :female =&gt; [&quot;Queenie&quot;, &quot;Ms. K&quot;]<br>  },<br>  :lives =&gt; {<br>    &quot;Subway&quot; =&gt; [&quot;Theo&quot;, &quot;Queenie&quot;],<br>    &quot;Central Park&quot; =&gt; [&quot;Alex&quot;, &quot;Ms. K&quot;, &quot;Lucky&quot;],<br>    &quot;Library&quot; =&gt; [&quot;Peter Jr.&quot;],<br>    &quot;City Hall&quot; =&gt; [&quot;Andrew&quot;]<br>  }<br>}</pre><p>My goal was to re-organize the data to create a hash that has a key for each pigeon, pointing to values that were hashes made up of keys that were symbols pointing to a value of an array. Woah, that seems complicated. I knew I needed to iterate through each hash, then iterate through each nested hash, then the arrays, and then piece it all back together to make the new structure that I was after. For the first of many times in my coding journey thus far, I pulled the whiteboard down from the wall of my office, grabbed some colorful dry erase markers, and got to work. A few hours later, I had created a method to make my new pigeon hash:</p><pre>def nyc_pigeon_organizer(data)<br>  pigeon_list = {}<br>  data.each do |characteristic, characteristic_hash|<br>    characteristic_hash.each do |trait, trait_array|<br>      trait_array.each do |name|<br>        if pigeon_list[name] == nil<br>          pigeon_list[name] = {}<br>        end<br>        if pigeon_list[name][characteristic] == nil<br>          pigeon_list[name][characteristic] = []<br>        end<br>        if data[characteristic][trait].include?(name)<br>          pigeon_list[name][characteristic] &lt;&lt; trait.to_s<br>        end<br>      end<br>    end<br>  end<br>  pigeon_list<br>end  </pre><p>Looking back at this code now, only a month after I wrote it, I can see some ways that I could try to improve my code. I wonder why I only used “each” and if I really needed to create so many empty hashes and arrays. But this was one of the first times I saw how powerful a few lines of code to iterate through a hash can be. I only wish I had taken a picture of the work I did on my whiteboard to solve this logic puzzle.</p><h3>Arguments can look like hashes? Neat!</h3><p>At the end of my first week at Flatiron, I was beginning the day by working through some discussion questions with my tablemates. The final question asked us to create a Car class that would allow for certain functionality to create new cars. The first way to instantiate an instance of the Car class was familiar to us. It called for two arguments, one string for the make and one string for the model.</p><pre>volvo_lightning = Car.new(&quot;Volvo&quot;, &quot;Lightning&quot;)</pre><p>However, the next part had us stumped.</p><pre>volvo_lightning = Car.new(make: &quot;Volvo&quot;, model: &quot;Lightning&quot;)</pre><pre>volvo_lightning.make #=&gt; &quot;Volvo&quot;<br>volvo_lightning.model #=&gt; &quot;Lightning&quot;</pre><p>How could you have symbols for make and model in the parentheses where we’re used to only seeing strings? We weren’t sure what to make of this, so we decided to see what class (make: “Volvo”, model: “Lightning”) is. Imagine our surprise when we saw that it’s a hash! How does Ruby know that?! It looks like a hash with keys and values, so it makes sense! Suddenly we knew how to work with this seemingly new structure. If we defined the hash as make_and_model, we could get the make with make_and_model[:make], and the model with make_and_model[:model]. Cool! We’d later learn more about what these symbols can do and even simpler ways to use them, but at the time, I was amazed by the power of the hash in Ruby.</p><h3>Using a hash to keep track of counts — so useful!</h3><p>When I really saw how useful hashes could be was when I was working with a partner through a project and we needed a way to organize information in a logical way. We had many ingredients, and some of them were allergens that some of our users were allergic to. We needed to return the ingredient that had the highest number of users allergic to it.</p><p>We thought about how we could complete this task, discussed some complicated-sounding ideas about creating count variables for each ingredient and incrementing them for each user, but then I remembered my favorite data structure — the hash! We could create a key for each ingredient and have it point to a value that was the count of the number of users allergic to it.</p><pre>class Ingredient<br>  <br>  def number_of_users_allergic<br>    allergens = Allergen.all.select {|a| a.ingredient == self}      <br>    allergens.count  <br>  end</pre><pre> def self.allergy_frequency<br>    x = {}<br>    all.each do |ingredient|<br>      x[ingredient]=ingredient.number_of_users_allergic<br>    end<br>    x<br>  end</pre><pre>end</pre><p>So, we had the hash, but that wasn’t the end of it. Which ingredient had the highest value? Can you sort a hash by its values? Of course you can! Then, we’d only need the final key in the hash, and we’d have our answer.</p><pre>class Ingredient</pre><pre>  def self.most_common_allergen<br>    allergy_frequency.sort_by {|key, value| value}[-1][0]<br>  end</pre><pre>end</pre><p>Hashes are pretty incredible. While they may seem simple at first, and then intimidating when they contain multiple levels of nesting, their structure and logic make them an amazing tool that Ruby provides for organizing and accessing information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb8bdb280" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>