<?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 Robin Kim on Medium]]></title>
        <description><![CDATA[Stories by Robin Kim on Medium]]></description>
        <link>https://medium.com/@imrobinkim?source=rss-637ee2c292ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*qBMGM_vE7OxaiYnRKLPuig.jpeg</url>
            <title>Stories by Robin Kim on Medium</title>
            <link>https://medium.com/@imrobinkim?source=rss-637ee2c292ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:34:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imrobinkim/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[Handling Asynchronous Actions with Redux Thunk]]></title>
            <link>https://medium.com/swlh/handling-asynchronous-actions-with-redux-thunk-86b8d8e0b83e?source=rss-637ee2c292ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/86b8d8e0b83e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Robin Kim]]></dc:creator>
            <pubDate>Mon, 24 Jun 2019 02:54:58 GMT</pubDate>
            <atom:updated>2020-06-21T17:44:06.513Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*uHumlKU6fado6sOF2eHVwg.jpeg" /></figure><p>Redux is a JavaScript library and design pattern that encourages single source of truth by decoupling state from complex component trees. This calls for a new way of making asynchronous actions as the vanilla React way consists of constantly fetching from inside lifecycle methods, such as componentDidMount, to update component states. There are three general ways React developers go about tackling this problem: Redux Promise Middleware, Redux Saga, and Redux Thunk. This short tutorial will explore Redux Thunk and how it handles asynchronous functions.</p><h3>Why Do We Need the Thunk Middleware?</h3><p>Redux Thunk is a middleware, meaning that it intercepts every action object before it reaches a reducer. The middleware ensures that the asynchronously-retrieved data will be added to the redux store accordingly. Here are the reasons why we need Redux Thunk as a middleware:</p><ol><li>Asynchronous actions are difficult to deal with because we have less control over the order in which actions get dispatched. Adding Redux Thunk allows us to fire everything in the order that we want because it’s able to stop everything until the request or fetch call is resolved.</li><li>Reducers must be pure functions. This stops us from making web requests from within reducers.</li><li>Actions must return plain JavaScript objects. Without our Redux Thunk middleware, Redux will error out if an action creator returns something other than a JS object (i.e. a Promise, function, or undefined).</li></ol><p>With Redux Thunk, actions no longer have to strictly return JavaScript objects! Action creators can return functions and these functions have access to certain parameters, including <strong>dispatch </strong>and<strong> getState</strong>.<strong> </strong>Because of this, action creators can dispatch multiple actions within itself and an action can be calibrated to be dispatched only after an asynchronous call has been resolved. Redux Thunk gives us the ability to fire actions in a specific order and thus, gives us a way of handling asynchronous actions in Redux.</p><h3>The Setup</h3><p>This short tutorial will go through the baseline requirements needed to set up Redux and Redux Thunk from scratch. We will make a call to the <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder API</a> to retrieve some posts data, which we will render on our main app container upon load of the page.</p><p>Start by creating a new app using create-react-app in your terminal, then navigate into the newly created directory to install redux, react-redux, and redux-thunk. Once these packages are added to your project, go ahead and start up your application with npm start.</p><pre>npx create-react-app project-redux-thunk<br>cd project-redux-thunk<br>npm install --save redux react-redux redux-thunk<br>npm start</pre><p>create-react-app starts us out with a basic setup of folders and files. Add two new folders within src and<strong> </strong>name them components and redux. Move the file App.js into the components folder and create three new files in the redux folder: actionCreators.js, reducer.js, store.js. The folder structure of your app should look something like this at this point:</p><pre>/public</pre><pre>/src<br>   /components<br>      /App.js<br>   /redux<br>      /actionCreators.js<br>      /reducer.js<br>      /store.js</pre><pre>App.css<br>App.test.js<br>indes.css<br>index.js<br>...</pre><p>Clean up index.js, edit its import pathways, and add the Provider component to pass down store (which we will create later on in redux/store.js).</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import &#39;./index.css&#39;;<br>import App from &#39;./components/App&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import store from &#39;./redux/store&#39;;</pre><pre>ReactDOM.render(<br>   &lt;Provider store={store}&gt;<br>      &lt;App /&gt;<br>   &lt;/Provider&gt;<br>   document.getElementById(&#39;root&#39;)<br>);</pre><p>Clean up components/App.js as well and add the connect method from react-redux so that the App.js file looks like this:</p><pre>import React, { Component } from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;</pre><pre>class App extends Component {<br>   render() {<br>      &lt;div className=&quot;App&quot;&gt;&lt;/div&gt;<br>   }<br>}</pre><pre>export default App;</pre><p>Now, let’s set up the middleware React Thunk within src/redux/store.js. We need to specify all of the middleware we are using when creating the Redux store. We do this by first using a Redux method called compose to set up an advanced store, which allows us to combine multiple middleware — in our case, Redux Thunk and Redux developer tools. We then use the method createStore, which takes in applyMiddleware within its second argument. src/redux/store.js should look as follows:</p><pre>import { createStore, applyMiddleware, compose } from &#39;redux&#39;;<br>import reducer from &#39;./reducer&#39;;<br>import thunk from &#39;redux-thunk&#39;; </pre><pre>const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; </pre><pre>const store = createStore(reducer, composeEnhancers(applyMiddleware(thunk))); </pre><pre>export default store;</pre><p>Next, we’ll edit actionCreators.js. As mentioned before, Redux Thunk allows action creators to return functions (instead of objects) that can dispatch other actions after a fetch call has been resolved. We&#39;ll the following lines of code to src/redux/actionCreators.js:</p><pre>const URL = &quot;https://jsonplaceholder.typicode.com/posts&quot; </pre><pre>function fetchedPosts(posts) {<br>   return { type: &quot;FETCHED_POSTS&quot;, posts }<br>} </pre><pre>function loadingPosts() {<br>   return { type: &quot;LOADING_POSTS&quot; }<br>} </pre><pre>function fetchingPosts(posts) {<br>   return (dispatch) =&gt; {<br>      dispatch(loadingPosts())</pre><pre>      fetch(URL)<br>         .then(res =&gt; res.json())<br>         .then(posts =&gt; {<br>            dispatch(fetchedPosts(posts))<br>         })  <br>   }<br>} </pre><pre>export { fetchingPosts };</pre><p>Here is what’s happening above: we make a fetch call to an endpoint of <a href="https://jsonplaceholder.typicode.com/posts">/posts of a JSONPlaceholder API</a>, which will return some Post objects or dummy data for us. We only need to export the function fetchingPosts at the end because it is the only function we will need to invoke from outside of this file. The rest of the functions declared from within actionCreators.js will be triggered by fetchingPosts. Once fetchingPosts is invoked (i.e. when a user visits the website to view a list of posts), the action created by loadingPosts is dispatched to indicate that we’re in the process of making a request to the API. Even though this process may only take a couple milliseconds, we can use this “loading” state to visualize the process to the user via a spinner or progress bar. Once we receive a response from the fetch call, the second action — created by fetchedPosts — is dispatched, indicating the the fetch process has ended successfully.</p><p>And the last of our redux folder — reducer.js.</p><p>Import combineReducers from redux so that we can combine multiple reducers (each accounting for a respective piece of state) into a single root reducer that will be exported into store.js to create our Redux store. src/redux/reducer.js:</p><pre>import { combineReducers } from &#39;redux&#39;; </pre><pre>const postsReducer = (oldState = [], action) =&gt; {<br>   switch (action.type) {<br>      case &quot;FETCHED_POSTS&quot;:<br>         return action.posts<br> <br>     default:<br>        return oldState<br>     }<br>}</pre><pre>const loadingReducer = (oldState = &quot;false&quot;, action) =&gt; {<br>   switch (action.type) {<br>      case &quot;FETCHED_POSTS&quot;:<br>         return false<br>      case &quot;LOADING_POSTS&quot;:<br>         return true<br>      default:<br>         return oldState<br>   }<br>}</pre><pre>const rootReducer = combineReducers({<br>   posts: postsReducer,<br>   loading: loadingReducer,<br>}) </pre><pre>export default rootReducer;</pre><p>As you can see, we have two reducers: postsReducer, which stores our Post objects in an array after the fetch has been made, and loadingReducer, which indicates the state of the fetch call. loadingReducer will come in handy when we want to implement a visual indicator, like a loading spinner or progress bar.</p><p>At this point, our application should be error-free and should show a blank page upon load of the browser.</p><p>Let’s revisit our App.js file to connect it to our redux portion of the app.</p><p>Import fetchingPosts from actionCreators.js and map it to the App component using mapDispatchToProps. Now that we have access to the action creator fetchingPosts within the App.js component, we can call it inside componentDidMount like so:</p><pre>import React, { Component } from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { fetchingPosts } from &#39;../redux/actionCreators&#39;;</pre><pre>class App extends Component {<br>   componentDidMount() {<br>      this.props.fetchingPosts();<br>   }</pre><pre>   render() {<br>      &lt;div className=&quot;App&quot;&gt;&lt;/div&gt;<br>   }<br>}</pre><pre>const mapDispatchToProps = (dispatch) =&gt; {<br>   return {<br>      fetchingPosts: () =&gt; { dispatch(fetchingPosts()) }<br>   }<br>}</pre><pre>export default connect(mapStateToProps, mapDispatchToProps)(App);</pre><p>Although we have nothing rendering on our page yet, if we go to our Redux developer tools, we will see that actions with types ‘LOADING_POSTS’ and ‘FETCHED_POSTS’ have been dispatched and our state has been updated with an array of Post objects!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfuPq3ZFJlj3B2wrMuYIUg.png" /></figure><p>Hooray! We’ve successfully fetched our Post objects and have updated our state with them using Redux and Redux Thunk! All we have to do now is get the data to show up on our page. To do that, we need to first introduce mapStateToProps method within App.js so that the App component can read the <strong>posts</strong> and <strong>loading</strong> pieces of our state. Then within the render method, we’ll save a collection of &lt;li&gt; elements of post titles in a variable called allPosts. src/components/App.js:</p><pre>import React, { Component } from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { fetchingPosts } from &#39;../redux/actionCreators&#39;;</pre><pre>class App extends Component {<br>   componentDidMount() {<br>      this.props.fetchingPosts();<br>   }</pre><pre>   render() {<br>      const allPosts = this.props.posts.map(post =&gt; &lt;li key={post.id}&gt;{post.title}&lt;/li&gt;)</pre><pre>      return this.props.loading ? &lt;div&gt;Loading...&lt;/div&gt; : (<br>         &lt;div className=&quot;App&quot;&gt;<br>            &lt;ul&gt;{allPosts}&lt;/ul&gt;<br>         &lt;/div&gt;<br>      )<br>   }<br>}</pre><pre>const mapStateToProps = (state) =&gt; {<br>   return {<br>      posts: state.posts,<br>      loading: state.loading<br>   }<br>}</pre><pre>const mapDispatchToProps = (dispatch) =&gt; {<br>   return {<br>      fetchingPosts: () =&gt; { dispatch(fetchingPosts()) }<br>   }<br>}</pre><pre>export default connect(mapStateToProps, mapDispatchToProps)(App);</pre><p>With these final edits to our code in App.js, our app will display the text “Loading…” for a quick moment as it fetches the Post objects from the API. Once our fetch call is resolved, the action created by the action creator fetchedPosts will be dispatched and our state property <strong>loading</strong> will go back to false. When this.props.loading evaluates to false again, the text “Loading…” will be replaced with an unordered list of 100 posts like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IEB6HDTEboz58MVPRj1JRA.png" /><figcaption>What our final product should look like!</figcaption></figure><p>You can find the complete project directory for this tutorial <a href="https://github.com/imrobinkim/project-redux-thunk">here</a>!</p><h3>Conclusion</h3><p>This tutorial quickly walked through a Redux Thunk implementation, including the organization and set up of the Redux store, reducers, and action creators. To recap: Redux allows us to decouple state from the components in our React application. While the Redux design pattern makes it easier to manage state in large, complex apps, we need a new way of making asynchronous calls. Redux Thunk offers a solution as it gives us more control over the order in which actions are dispatched within asynchronous processes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86b8d8e0b83e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/handling-asynchronous-actions-with-redux-thunk-86b8d8e0b83e">Handling Asynchronous Actions with Redux Thunk</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Takeaways from Building Intelligent Data Lakes Workshop]]></title>
            <link>https://imrobinkim.medium.com/takeaways-from-building-intelligent-data-lakes-workshop-f1001c253498?source=rss-637ee2c292ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1001c253498</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[slalom]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Robin Kim]]></dc:creator>
            <pubDate>Sat, 08 Jun 2019 19:58:23 GMT</pubDate>
            <atom:updated>2021-05-21T20:31:05.520Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the greatest assets of living near a metropolitan city and a growing tech hub is the easy access to great events and meetups. Last Thursday, I had the opportunity to attend an event hosted by Slalom, AWS, and Women in Big Data titled “AWS: Building Intelligent Data Lakes” in Arlington, VA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ncVy_otSlswtFzhGIhzmHg.jpeg" /></figure><p><a href="https://www.womeninbigdata.org/">Women in Big Data</a> (WiBD) is a volunteer-based forum that connects and celebrates female talent in the field of big data and analytics. It began with 15 members from Intel and has expanded to a member count of over 8,500. The <a href="https://www.aauw.org/research/solving-the-equation/">American Association of University Women</a> (AAUW) reported in 2015 that only 12% of working engineers were women and barely 18% of all computing degrees went to women. WiBD is working to bridge the gender gap that exists and to grow women representation in the field of Big Data to 25% by 2020.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*JDCoJQ59M2TvCOtR2Oh1ag.png" /></figure><p><a href="https://www.slalom.com/">Slalom</a> is a modern consulting firm that blends design, engineering, and analytics to help businesses successfully implement strategies and brand goals. They offer a list of services including cloud integration, AI solutions, UI/UX design, and data analysis. Their Practice Area Director, Paul Beda, shared examples of customer success stories (which I write more about later in the post) that involved the use of big data and AWS tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*kTL7_H8govub3khEwxmkSw.png" /></figure><p>A subsidiary of Amazon, <a href="https://aws.amazon.com/">Amazon Web Services</a> (AWS) offers cloud computing web services and platforms. It provides over 165 services including compute, storage, databases, analytics, machine learning and artificial intelligence, application development, deployment, and management.</p><p>Rielah De Jesus — a Solutions Architect at AWS —explained how data should be regarded as a strategic asset by all companies because of its ability to create robustly predictive models. With good reason because <a href="https://www.forbes.com/sites/rkulkarni/2019/02/07/big-data-goes-big/#ff78f4b20d7b">Forbes</a> predicts the revenue of the big data market to be $200 billion by 2020. However, many companies are oblivious to the potential of their isolated data and even then, <a href="https://www.techrepublic.com/article/85-of-big-data-projects-fail-but-your-developers-can-help-yours-succeed/">85% of big data projects fail</a>. Why? One of the biggest reason is the hefty cost and challenge of moving data across silos.</p><p>Enter, Data Lake.</p><p>Data lake is a way to store and analyze massive volumes and heterogeneous types of data. Through this method, all data is held in a central repository in its native format, meaning that it is highly accessible and can be quickly ingested and transformed. In short, data lakes facilitate easy usage of data and brings functionality to it.</p><p>AWS provides an array of services that together enables the lifecycle of data lakes. These products address four key characteristics:</p><ul><li><em>Collect anything</em>: can collect any type of data, from multiple sources (i.e. connected devices, web logs/cookies, social media, transactions, etc…)</li><li><em>Dive in anywhere</em>: can go in at any point within data lake to retrieve info</li><li><em>Flexible access</em>: grants access to any and all departments and authorized individuals making use of the data &amp; allows for integration of other AWS tools</li><li><em>Future proof</em>: withstands time and new technology</li></ul><p>De Jesus told us that AWS products can be used like lego pieces in building various architectures of data analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7j-f4qK5qJQH59Z0hE_R8w.jpeg" /><figcaption>Example of how multiple AWS products can be linked together to collect, store, and analyze data</figcaption></figure><p>After an introduction to AWS, we were given materials to a three-part workshop that walked us through building our own data lake and analysis architecture.</p><h4>Lab 1: Hydrate the data lake using Kinesis Platform</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8Ir5trV9gIc6CxGL5rznA.png" /><figcaption>Lab 1. Provided by Amazon Web Services</figcaption></figure><p>This lab consisted of using Kinesis Streams to collect and store streaming IoT sensor data, then using Kinesis Analytics to analyze the streaming data in real-time. We used a built-in, machine learning algorithm called RANDOM_CUT_FOREST, which serves to detect anomalies in streaming data. In the final portion of this lab, we used Kinesis Firehose to export data in both raw and processed forms into S3 — a storage service that allows for further analysis. This lab highlighted the flexibility of Amazon Kinesis in allowing multiple consumers to read and process data from the same stream. In our case, our first consumer was Kinesis Analytics, which analyzed the data in real-time and stored the result in S3, and our second consumer was Kinesis Firehose, which stored raw data directly in S3.</p><h4>Lab 2: Catalog, Transform and Visualize using Glue, Athena, EMR, Redshift Spectrum and QuickSight</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhcivnZwB0BJx5fKDT4faA.png" /><figcaption>Lab 2. Provided by Amazon Web Services</figcaption></figure><p>In Lab 2, we populated the AWS Glue Data Catalog with our data stored in the S3 bucket from Lab 1. The data catalog holds references to the location, schema, and runtime metrics of data. AWS Glue uses these references to target, extract, and transform data. We learned that columnar store formats, such as Parquet (as opposed to CSV), are optimal when it comes to storing data because it means fewer bytes to read and better query performance. After transforming the CSV data (retrieved from S3) into Parquet using AWS Glue, we used Athena to query the data and QuickSight to visualize the data in various graph forms. We were also given the option to use EMR (Elastic MapReduce) and Redshift Spectrum to query the data.</p><h4>Lab 3: SageMaker</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STEcdYRnn-ft4tRaMQpKJQ.png" /><figcaption>Lab 3. Provided by Amazon Web Services</figcaption></figure><p>The final lab involved the integration of Amazon SageMaker to train, create, and host a machine-learning model that detects anomalies. We prepared the data with AWS Glue, then used a built-in machine learning algorithm called K-Means algorithm on the transformed data. This function invokes an endpoint for prediction, which can be used to program reactive measures to anomalies in our applications.</p><p>Slalom’s Practice Area Director, Paul Beda, shared a customer success story about their client Avis Budget Group that helped to illustrate a practical use of data and analysis tools like the ones provided by AWS. The sudden upsurge in ridesharing services like Uber and Lyft hit car rental companies hard and Avis Budget Group needed a smart way to keep inventory of vehicles and cut down on unnecessary costs. Slalom compiled an extensive amount of data on how the vehicles were being used (i.e. they found that some were being rented out by Uber drivers who were driving back and forth within a defined space) and came up with an efficient and feasible system of garage organization. This solution involved parking the most utilized vehicles in portions of their garages with easier access. Beda also talked about innovative ways of using and selling data. For instance, cars with the ability to detect potholes or certain weather conditions (i.e. when windshields are on) can relay that information to city halls or weather forecast systems. Smart data usage can also actualize an age of personalization. We can imagine a near future with rental cars and hotel rooms that preset the temperature and radio or TV channels based on previous preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UN57RQeMbI6G7EOv3KwHw.jpeg" /><figcaption>Panelists discussing topics of cloud computing and diversity</figcaption></figure><p>One of the panelists, Amy Tseng, a Database Admin. Manager at Fannie Mae, said she led her team in the transition to cloud because of some of the challenges they faced regarding scalability, concurrency, provisioning, and security. Another key issue was the time it took to transport big data. AWS provided solutions for all these challenges, including a cut in transport time from two weeks to a couple of hours. With a growing list of available products and services, AWS is sure to provide feasible solutions for many business needs and agendas.</p><p>I want to thank AWS, Slalom, and Women in Big Data for an amazing afternoon of learning and for their dedication to supporting and growing women representation in the tech industry. It was an invaluable experience listening to some of these female leaders and learning how to leverage AWS services when working with big data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1001c253498" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Babel and Webpack’s Role in create-react-app]]></title>
            <link>https://imrobinkim.medium.com/babel-and-webpacks-role-in-create-react-app-3a827ad460a2?source=rss-637ee2c292ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a827ad460a2</guid>
            <category><![CDATA[flatiron-school]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Robin Kim]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 17:48:11 GMT</pubDate>
            <atom:updated>2021-05-21T20:35:52.307Z</atom:updated>
            <content:encoded><![CDATA[<p>With the introduction of Facebook’s <a href="https://github.com/facebook/create-react-app">create-react-app</a> CLI tool, much of the configuration and labor of setting up React.js applications were abstracted away. While this one-liner command is too good to be true, it is helpful to understand some of the mechanisms going on under the hood. Two important configuration tools that create-react-app sets up for us are Babel and Webpack. What are they and why do we need them in our React.js applications?</p><h3>Babel</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ci7Opy7BG-xsZH782UqrCQ.png" /></figure><p>Babel is a JavaScript compiler that translates newer ECMAScript 2015+ code into code that older web browsers can natively understand and read. This is especially important because JavaScript is an ever evolving language. For instance, arrow functions, “let” and “const” , and class syntax were absent in ES5. The confoundedness of various JavaScript versions and the inability of some browsers to support newer language features of ES6 propelled Babel to popularity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_rrYtuohClYoktaYkPC4Q.png" /><figcaption>Example of Babel converting newer code into its ES5 equivalent (taken from <a href="https://babeljs.io/docs/en/">https://babeljs.io/docs/en/</a>)</figcaption></figure><p>Specific to developers working with React.js, Babel is used to convert JSX syntax into JavaScript via the Babel preset “react”.</p><h4>Why use Babel if most browsers today already support ES6+ syntax?</h4><ol><li><em>For convenience</em>. It allows developers to write shorter code that is then processed by Babel into compliant JavaScript that would otherwise be lengthy to write out. For instance, developers are able to use non-standard JSX thanks to Babel.</li><li><em>For flexibility. </em>Babel is able to compile syntactic sugar and language features that isn’t yet a part of ECMAScript. In fact, it can compile features that may never be part of ECMAScript. Different Babel plugins make this possible.</li></ol><h3>Webpack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94ZhvvcXzyzCwuUVjxljhA.png" /></figure><p>Webpack is a module bundler and task runner. This tool allows us to combine different files in our project directory, meaning we can import Javascript code from one file to another. Webpack packages every file and dependency — i.e. all components, npm modules, jQuery, etc. — needing to be imported into one big JavaScript file. This is very convenient because when the client sends a request to our React application, the application only has to transfer a single, compiled file. Webpack is a lifesaver in this aspect. It pre-digests the many files of code in our application and bundles them — along with all of the dependencies — into one file.</p><p>Babel and Webpack work under the hood in React.js applications that are set up using the create-react-app command. While create-react-app is a convenient and fast way of starting a project, you may want to consider configuring these tools manually to fit the needs of your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a827ad460a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How State Updates Are Merged in React]]></title>
            <link>https://imrobinkim.medium.com/how-state-updates-are-merged-in-react-e07fc669fec2?source=rss-637ee2c292ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/e07fc669fec2</guid>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[flatiron-school]]></category>
            <dc:creator><![CDATA[Robin Kim]]></dc:creator>
            <pubDate>Thu, 31 Jan 2019 04:26:25 GMT</pubDate>
            <atom:updated>2019-02-02T06:03:23.169Z</atom:updated>
            <content:encoded><![CDATA[<p>Perhaps one of the rare instances being shallow is welcomed...</p><p>Before we get into shallow merging though, let’s talk briefly about React Components and state. React Components help us break down the user interface (UI) into smaller parts, keeping our code organized and modular. We are able to send data down from parent components to child components via props, which holds data that can be used to describe what should be rendered to the DOM. Once passed down to a child component, props cannot be changed internally.</p><p>Enter State. State allows React components to modify their output in response to user input. This allows for more dynamic application UIs. According to <a href="https://reactjs.org/docs/react-component.html#state">React docs</a>, however, state should never be directly modified. This is because a manual state mutation can be overwritten later on by asynchronous functions (leading to hard-to-trace bugs and major headaches). Instead, React provides us with the method setState( ).</p><p>setState( ) is a method that is available to all React components. Invoking it lets React know that the component state has been changed. We can use it by passing in a new version of the state via an object literal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkADRtY7f7eB4tFa3w_kyw.png" /></figure><p>In the figure above, we initialize a state object with the property of “name” set to a string value of “Bob” and another property of “isLoggedIn” set to a boolean of “false” within the class’s constructor method (lines 7–13). A logging in action (e.g. clicking a login button) will trigger the callback function “handleLogIn”. Within this handler, a setState( ) method is invoked to update the initial state (line 16).</p><p>It is important to note here that React merges the object you provide within the setState( ) method into the current state object you are working with. In other words, only the “isLoggedIn” is updated to be “true”, while the remaining variable “name” (with value ‘Bob’) is left intact. This means that we do not have to pass in an object that lists out all of the properties of the state object. We just have to supply the setState( ) method with the key/value pair(s) for which we would like to update the value. All thanks to shallow merging.</p><p>At this point the newly updated state object will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*J04NTHGLbIP3tPGPfhGTnA.png" /></figure><p>The value of “isLoggedIn” was changed to “true” while the key/value pair “name: ‘Bob’” was left untouched.</p><p>Shallow merging only merges things on the first level though (hence the term shallow), which means that we have to be careful when we use setState( ) on state objects with nested structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*cknkW9RBvruYr6SoBgC5Dg.png" /><figcaption>Example of a state object with a nested structure</figcaption></figure><p>Following the logic of shallow merging, you might try to update the value of “address.city” for the state object illustrated above with the method setState( ) like this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ls_9FDurriBhPf374FeZHw.png" /><figcaption>Attempt to update the value for “address.city” while keeping the other information intact</figcaption></figure><p>However, this will change the state object’s structure to look something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_C5B2F5egQCHsCJIqT359Q.png" /></figure><p>As you can see, we lost “address.street” within the state object because the nested object (value of the key “address”) got overwritten by a new object with a single key of “city”. The logic of shallow merging does not apply for nested objects.</p><p>How do we update the value for “address.city” without totally overwriting the nested object (and thus saving the “address.street” information)? In other words, is there a way to deep merge? There are multiple ways to tackle this but the spread operator provides us a feasible solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*pu-NzHyT5oeBXawCfsIsog.png" /></figure><p>The code above is a redo of the setState( ) implementation. We pass in a new version of state holding the key of “address”. The value of this new object being passed into setState( ) includes a spread operator, which returns all of the keys and values from within the initial “this.state.address” object. Since this initial “this.state.address” object already had a key of “city”, supplying a new value for the key of “city” will overwrite the original value. If a key of “city” hadn’t been in the original “this.state.address” object, it will have been added via this setState( ) method.</p><p>With this implementation of setState( ) the updated state object will look like (with the “address.street” information still intact):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uF_cc7p310JWwsrIqiCnjQ.png" /><figcaption>Yay! Just what we needed!</figcaption></figure><p>To recap, React.Component’s setState( ) uses shallow merging to update state, ultimately saving us from listing out all of the keys and values from the initial state object. We can’t, however, apply the same logic of shallow merging on nested state objects. For these kinds of object structures, we can make use of the handy spread operator.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e07fc669fec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be Gone Superfluous Tables! — How Active Record Allows Us to Refer to Different Types of a Model]]></title>
            <link>https://imrobinkim.medium.com/be-gone-superfluous-tables-how-active-record-allows-us-to-refer-to-different-types-of-a-model-f66091fd9e80?source=rss-637ee2c292ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/f66091fd9e80</guid>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[flatiron-school]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Robin Kim]]></dc:creator>
            <pubDate>Wed, 02 Jan 2019 01:13:18 GMT</pubDate>
            <atom:updated>2020-06-22T19:12:35.905Z</atom:updated>
            <content:encoded><![CDATA[<h3>Be Gone Superfluous Tables: How Active Record Allows Us to Refer to Different Types of a Model</h3><p>Let’s say we have a User model that has associations with the models Listing and Review, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*2bH-kPBNoywZ81uUecZeqA.png" /></figure><p>But as we are building these associations we realize that we want to make it so that a certain type of User — a host — has many listings and a certain type of User — a guest — has many reviews.</p><p>-<strong>Listing</strong> belongs to a specific type of User — <em>a host</em>.<br>-<strong>Review </strong>belongs to a specific type of User — <em>a guest</em>.</p><p>We can consider creating separate tables for these two types of users but what if we want the User to be able to switch back and forth from being a guest to a host? Fortunately, Active Record offers a solution for this exact situation via the foreign_key and class_name arguments, which we can add in our model definitions.</p><p>For this implementation, we start by establishing a Listing belongs_to a host relationship. If we stop here though, Active Record will default to looking for a table named hosts whenever a related query is made, which is problematic because we won’t be creating a separate model or table for Host. The key here then is specifying which table hosts is referring to — in our case, the table users— and we can do that using the class_name argument. We can do the same for the Review model, which has a belongs_to relationship with guest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujRD_wjcz1mBYQiSzSO9xA.png" /><figcaption>&lt;app/models/listing.rb&gt;</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWr3mTOhlF7fJJPyTQo-5w.png" /><figcaption>&lt;app/models/review.rb&gt;</figcaption></figure><p>We also have to include the foreign keys host_id in the listings table and guest_id in the reviews table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*gX1aIJ9hb_WgZCD87RNXZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZOVYOc84vEuzSpBwEswqw.png" /><figcaption>&lt;db/schema.rb&gt;</figcaption></figure><p>Additionally, we need to establish two has_many relationships under the User model. We also have to specify which foreign keys Active Record should look for in each respective table. Otherwise Active Record will default to looking for a foreign key called user_id (instead of host_id or guest_id ). This is made possible with the foreign_key argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*dvVOH6IDLa32Hf9UNjxLbg.png" /><figcaption>&lt;app/models/user.rb&gt;</figcaption></figure><p>Through the associations we’ve created above, a user can now have many listings as a host <em>and</em> many reviews as a guest. Utilizing the class_name and foreign_key arguments saves us from having to create unnecessary tables that may actually end up muddying relationships between models. Cool trick, Active Record!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f66091fd9e80" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>