<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Derek Brimley</title>
    <description>The latest articles on DEV Community by Derek Brimley (@derekbrimley).</description>
    <link>https://dev.to/derekbrimley</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F15880%2F95cd1dd3-50c1-485d-a49a-7f990dc91791.jpeg</url>
      <title>DEV Community: Derek Brimley</title>
      <link>https://dev.to/derekbrimley</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/derekbrimley"/>
    <language>en</language>
    <item>
      <title>Making Consistent React Forms Using a Higher-Order Component</title>
      <dc:creator>Derek Brimley</dc:creator>
      <pubDate>Sat, 04 Nov 2017 17:11:58 +0000</pubDate>
      <link>https://dev.to/derekbrimley/making-consistent-react-forms-using-a-higher-order-component-2oc</link>
      <guid>https://dev.to/derekbrimley/making-consistent-react-forms-using-a-higher-order-component-2oc</guid>
      <description>&lt;p&gt;Forms can be a tricky part of a React app. While it would be nice to have a unified way to create a form, the forms also need to be customizable. Forms can have different styles, use different validation methods, and are submitted in different ways (i.e. to an API endpoint or a typical form submission). In our app, we have tried several ways of structuring forms, and now each form handles these issues slightly differently. We decided to come up with a solution that could be used throughout the whole app that will be flexible enough to handle the different cases, but also provide useful functionality.&lt;/p&gt;

&lt;p&gt;The pattern we are using is known in some places as a Function as a Child Component. &lt;a href="http://americanexpress.io/faccs-are-an-antipattern/"&gt;Some have labeled this an anti-pattern&lt;/a&gt;, but &lt;a href="https://medium.com/merrickchristensen/function-as-child-components-5f3920a9ace9"&gt;others have argued&lt;/a&gt; that it is more capable than normal, boring old higher-order components. For now, it works. Maybe one day we will realize the error of our ways and refactor it to the cool new pattern of the future. But today is not that day.&lt;/p&gt;

&lt;p&gt;We wanted a minimalist component that does a few things for us:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Sets the default values for each field, and keeps track of any changes, and if they have been touched.&lt;/li&gt;
&lt;li&gt;Returns an object with error messages.&lt;/li&gt;
&lt;li&gt;Keeps track of whether or not the form is valid to submit.&lt;/li&gt;
&lt;li&gt;Supplies a function that can be used to call a submit function.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The basic outline of the function looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;FormContainer fieldDefaults={fieldDefaults} errorFuncs={errorFuncs} onSubmit={onSubmit}&amp;gt;
  {({ fields, errorValues, triggerSubmit, submitDisabled }) =&amp;gt; {
    return(...)
  }}
&amp;lt;/FormContainer&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So the form takes a set of defaults, a set of functions to validate the fields, and a submit function. The component returns a list of field values, any errors, a function to trigger a submit, and a boolean of whether or not the form is valid. With that, you can structure the form however you want, and it will be easy in the future to rearrange or update the form fields or logic.&lt;br&gt;
The component definition is fairly simple. Setting the state is a little complex, so I’ll explain it in detail.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;state = {
  fields: {
    ...Object.keys(this.props.fieldDefaults).reduce((acc, curr) =&amp;gt; (
      {
        ...acc,
        [curr]: {
          value: this.props.fieldDefaults[curr],
          isDirty: false,
        },
      }
    ), {}),
  },
  errorFuncs: this.props.errorFuncs,
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To understand what’s going on here, you’ll need to understand two things. First, the reduce function, which you can read up on here. Second, object destructuring, which you can learn about here.Â &lt;/p&gt;

&lt;p&gt;Basically, this sets the initial state of the form. The container is sent in an object with key-value pairs of the name of the field and the initial value of that field. This function creates an object with the key â€˜field’ with an object for each field inside. Each field object has a value (which the container is given) and an initial â€˜isDirty’ value (false). The â€˜isDirty’ value is used so the container knows if the field has been changed by the user yet, so no errors will show up before then. After the function runs, the state might looks something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  fields: {
    firstName: {
      value: '',
      isDirty: false,
    },
    lastName: {
      value: '',
      isDirty: false,
    },
    email: {
      value: '',
      isDirty: false,
    },
  },
  errorFuncs: { ... }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The component formats the data it will send back, and sends it through by rendering its children with parameters:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
  this.props.children({
    fields, errorValues, onChange, triggerSubmit, submitDisabled
  })
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The onChange function sets a new field value in the state, and sets the â€˜isDirty’ field to true.&lt;/p&gt;

&lt;p&gt;Solving React forms this way gives you total control over how the form is displayed, but you still get validation, errors, and all the benefits of a controlled form. We’ve been using this component for our forms for a little while now, and I’ve liked the simplicity and consistency of it.&lt;br&gt;
Anything you would have done differently? Questions about how the above works? Let me know, I’m always looking to improve!&lt;/p&gt;

</description>
      <category>react</category>
      <category>hoc</category>
      <category>forms</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Dynamic Custom Google Map Markers</title>
      <dc:creator>Derek Brimley</dc:creator>
      <pubDate>Tue, 17 Oct 2017 23:13:09 +0000</pubDate>
      <link>https://dev.to/derekbrimley/dynamic-custom-google-map-markers-a4</link>
      <guid>https://dev.to/derekbrimley/dynamic-custom-google-map-markers-a4</guid>
      <description>&lt;p&gt;I work on a React app with a Google Maps component (using the awesome &lt;a href="https://github.com/tomchentw/react-google-maps"&gt;react-google-maps&lt;/a&gt; package). The map displays a bunch of real-time data, and it is important that the marker icons are dynamic. Unfortunately, Google Maps doesn’t make it easy. The marker object expects an image, not a dynamic React component, so I needed a workaround to get the marker icons to reflect the changing data.&lt;br&gt;
The map marker accepts an image as a parameter, typically a path to a raster image. To be dynamic, it needed to be a SVG image, but it didn’t seem like that was an option. However, my coworker then told me to look into data URIs. After some research, I learned that I could use data URIs to ‘trick’ the map marker into accepting an SVG.&lt;br&gt;
A data URI is a string that defines an image in a specified format. The format is specified right in the string. The string looks something like this:&lt;br&gt;
&lt;code&gt;data:image/svg;base64,REQFUfju93$T…&lt;/code&gt;&lt;br&gt;
From &lt;a href="https://css-tricks.com/data-uris/"&gt;CSS Tricks&lt;/a&gt;, the format of the string should be:&lt;br&gt;
&lt;code&gt;data:[&amp;lt;mime type&amp;gt;][;charset=&amp;lt;charset&amp;gt;][;base64],&amp;lt;encoded data&amp;gt;&lt;/code&gt;&lt;br&gt;
You can use any type of data encoding, or none. A simple SVG data URI could be defined:&lt;br&gt;
&lt;code&gt;data:image/svg+xml;utf8,&amp;lt;svg&amp;gt;&amp;lt;rect stroke='black' fill='black' width='50' height='25'/&amp;gt;&amp;lt;/svg&amp;gt;&lt;/code&gt;&lt;br&gt;
It’s that simple! Data URIs are awesome for a lot of reasons, one being that they can make displaying images a lot faster, because the page doesn’t have to make so many HTTP requests. Instead, the image is just defined in code.&lt;br&gt;
For my purpose, I needed the image to be in the form of a string, so this seemed like a perfect solution. However, I still needed a way to convert a React SVG node into a string. Luckily, React provides an easy function to convert a React component into a string. Actually, they provide two: One called &lt;code&gt;renderToString&lt;/code&gt;, which returns the HTML that React would create from that component, and another called &lt;code&gt;renderToStaticMarkup&lt;/code&gt;, which does the same, but without all the extra React-specific attributes. I didn’t want any extra data-attributes, so I used renderToStaticMarkup.&lt;br&gt;
From there, it’s pretty simple to define a dynamic SVG, run it through the &lt;code&gt;renderToStaticMarkup&lt;/code&gt; function, and create the data URI string. If you want, you could also encode that string, but don’t forget to specify which encoding you used in the URI.&lt;br&gt;
The marker component ends up looking like this:&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;Marker icon={"data:image/svg+xml;utf8,&amp;lt;svg&amp;gt;&amp;lt;rect stroke='black' fill='black' width='50' height='25'/&amp;gt;&amp;lt;/svg&amp;gt;"} /&amp;gt;&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;One other issue that I ran into is forgetting to add &lt;code&gt;xmlns=http://www.w3.org/2000/svg&lt;/code&gt; to the SVG. Usually this attribute isn’t necessary to display an SVG in an HTML5 document, but when serving the image as a data URI, it still is. Don’t forget!&lt;br&gt;
I’m still pretty new with SVGs, so if I got something wrong, let me know! I’d love the feedback. It’s taken me a little while to get used to them, but I am having lots of fun figuring them out.&lt;br&gt;
If you are interested, &lt;a href="https://codepen.io/derekbrimley/pen/PJxwqP?editors=1000"&gt;here is a CodePen of the SVG icon I was working on&lt;/a&gt;. And here is an article about data URIs. And &lt;a href="https://css-tricks.com/lodge/svg/09-svg-data-uris/"&gt;here’s an article about SVG data URIs&lt;/a&gt;.&lt;br&gt;
Thanks for reading!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Handling Side Effects With Redux-Saga</title>
      <dc:creator>Derek Brimley</dc:creator>
      <pubDate>Fri, 28 Jul 2017 23:38:07 +0000</pubDate>
      <link>https://dev.to/derekbrimley/handling-side-effects-with-redux-saga</link>
      <guid>https://dev.to/derekbrimley/handling-side-effects-with-redux-saga</guid>
      <description>&lt;h2&gt;
  
  
  Why you should be using Sagas in your ReduxÂ app
&lt;/h2&gt;

&lt;p&gt;I recently joined a cool software startup, where we are building an equipment management software. Part of the application is a page called MapTrac, which is a single-page, auto-reloading map view of the equipment that a client manages. The data this page uses is constantly updating in the background, so it is difficult to make it a fast and smooth experience for end users. It is also tricky to keep fetching new data without stopping the rest of the application from running.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F4oijf5lpvxqf3uw6p8tv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F4oijf5lpvxqf3uw6p8tv.png" title="MapTrac page" alt="alt text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To help solve these problems, we use a cool, open-source library called Redux-Saga. Obviously, this library relies on Redux to work (it is a Redux middleware). As I said, I’m fairly new to the company, so I don’t fully understand the library myself, which is why I am writing this post. Hopefully by the end I understand it better!&lt;/p&gt;

&lt;h2&gt;
  
  
  Redux?
&lt;/h2&gt;

&lt;p&gt;First things first, what is Redux? From what I understand, Redux is a tool that helps keep your  application, specifically the data it uses, reliable. The philosophy behind Redux is that your application has a single source of “truth”â€Š–â€Šthat is, your app’s state. This state (or store, in Redux-speak) is read-only, which means that it can only be updated by calling an action. Actions are basically objects that tell your app that something happened: the user clicked a button, data was received, or anything else that might affect the state of your app.&lt;/p&gt;

&lt;p&gt;The action, in turn, calls a reducer, which is a pure function. If you aren’t sure what a pure function is, you can go &lt;a href="https://medium.com/r/?url=http%3A%2F%2Fwww.nicoespeon.com%2Fen%2F2015%2F01%2Fpure-functions-javascript%2F" rel="noopener noreferrer"&gt;here&lt;/a&gt; to learn more. Basically, it is a function that doesn’t update anything outside of its scope. For a reducer, it means that it creates a new state, based on what the action tells it, rather than updating the old one. It then returns the new state, which replaces the old state. This might seem tedious, but it helps your application behave consistently, and maintain control of your state. Redux forces you to go through this process so that you can always easily know why your state has changed. &lt;a href="http://redux.js.org/docs/introduction/Motivation.html" rel="noopener noreferrer"&gt;There are other reasons to use Redux&lt;/a&gt;, but that’s the main one: if you are worried about having a large, complicated, frequently-updating data store, then Redux can help you manage it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F481drb5xrksyvr4t4jl5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F481drb5xrksyvr4t4jl5.png" title="Redux-Sagas logo" alt="alt text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What Problem Does SagasÂ Solve?
&lt;/h2&gt;

&lt;p&gt;It isn’t all rainbows and unicorns in Redux-land. While Redux goes a long way in reducing side-effects that can affect your state, asynchronous tasks like getting data from your server can still be a pain with plain Redux. Sagas is a Redux middleware that makes handling those cases easier, and more pure. We’ll get to how it does that in a bit, but first, let’s go over the basic concepts behind asynchronous programming.&lt;/p&gt;

&lt;h3&gt;
  
  
  What’s the deal withÂ async?
&lt;/h3&gt;

&lt;p&gt;Talking about the difference between synchronous and asynchronous functions can be very confusing, because it seems backwards to what you would expect. In everyday vernacular, synchronous means that two things exist at the same time (i.e. they are “in sync”), while asynchronous means that two things do not exist at the same time. This is flipped in computer-speak. If a process or task is synchronous in Javascript, it means that it is dependent in some way on another process. Often, this means that a process cannot be started until another is finished. Asynchronous tasks, on the other hand, do not depend on any other task, and thus can be run independently.&lt;/p&gt;

&lt;p&gt;Often, this subject is confused with the idea of threads, and while they are interconnected, they are not the same. Both synchronous and asynchronous processes can be run in a single or multiple threads. For a visual example, &lt;a href="https://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean/748235#748235" rel="noopener noreferrer"&gt;see this excellent StackOverflow answer&lt;/a&gt;. Another response on that StackOverflow question provides a helpful metaphor to remember the difference between asynchronous and synchronous tasks:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;SYNCHRONOUS&lt;br&gt;
You are in a queue to get a movie ticket. You cannot get one until everybody in front of you gets one, and the same applies to the people queued behind you.&lt;/p&gt;

&lt;p&gt;ASYNCHRONOUS&lt;br&gt;
You are in a restaurant with many other people. You order your food. Other people can also order their food, they don’t have to wait for your food to be cooked and served to you before they can order. In the kitchen restaurant workers are continuously cooking, serving, and taking orders. People will get their food served as soon as it is cooked.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  What Does This Have To Do WithÂ Sagas?
&lt;/h3&gt;

&lt;p&gt;Good question! As I mentioned before, Sagas is used to make it easier to manage asynchronous (independent) tasks, especially when it comes to their effect on the state of your application. While there are benefits to using asynchronous tasks (&lt;a href="https://medium.com/r/?url=https%3A%2F%2Fnodesource.com%2Fblog%2Fwhy-asynchronous%2F" rel="noopener noreferrer"&gt;such as removing costly I/O blocking calls&lt;/a&gt;), they can be notoriously difficult to manage. They are less predictable than synchronous tasks, so you can’t depend on them to return a value in time for other blocks of code to use.&lt;/p&gt;

&lt;p&gt;Sagas separate the different kinds of code, which allows you to benefit from the asynchronous tasks while not blocking the rest of your application from running. In effect, Sagas runs on its own thread, which keeps the two blocks of code from interfering with each other. As an example, consider an application that needs to grab data from a database every time a specific Redux action is called. Using only synchronous code, the application would come to a halt every time that action is called. Using Sagas, it is possible to make these database calls in the background, while the application continues to run. The  data is fetched, and it updates the state, without interrupting the application’s flow.&lt;/p&gt;

&lt;p&gt;This is just one example of a “side effect that Sagas can help with. Remember, a side effect happens when a procedure affects something outside it’s scope. Other long-running or “impure tasks (such as interactions with browser cache) may be improved by moving them into a Saga.&lt;/p&gt;

&lt;h2&gt;
  
  
  When Should You UseÂ Sagas?
&lt;/h2&gt;

&lt;p&gt;Sagas is a powerful tool, and like all tools, you should carefully consider whether or not it is the right one for your use case. Some of these considerations include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Will it simplify your code?&lt;/li&gt;
&lt;li&gt;Will it improve the experience for the end user?&lt;/li&gt;
&lt;li&gt;Does your application rely on asynchronous tasks?&lt;/li&gt;
&lt;li&gt;Is introducing Sagas worth the additional complexity?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;While we use Sagas at our company, it doesn’t make sense in every situation. In fact, we recently reconsidered the worth we were getting from using the technology. Although we determined that it currently makes sense to continue to rely on it, that may not always be the case. You shouldn’t use a technology just because it can give you some benefit. You should weigh the pros and cons, and use Sagas if the benefits outweigh the drawbacks, subtracting the opportunity cost of the time, effort, and money it will take to implement it. Here are a few of the pros and cons, as I see it:&lt;/p&gt;

&lt;h3&gt;
  
  
  Pros
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Can significantly speed up application, especially one that relies on fetching new data regularly (such as in single-page applications).&lt;/li&gt;
&lt;li&gt;Separates UI components from business logic, which can make your code more organized and understandable.&lt;/li&gt;
&lt;li&gt;Sagas are great for doing automated testing because they use &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator" rel="noopener noreferrer"&gt;generator functions&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Cons
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Despite what I wrote above, Sagas introduces a lot of complexity, which can hinder understanding.&lt;/li&gt;
&lt;li&gt;Just because you are doing it in the background, you can still slow down your application with too many requests.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Sagas can be a very useful tool, if you know how to use it. It can help you and your organization leverage new technologies to make your application better organized, more easily maintained, and a smoother experience for the end user. To continue to learn more, below are some useful links. Also, I’m still learning, so if I got anything wrong, or I missed something important, please let me know! I’d love to get some feedback.&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;

&lt;h2&gt;
  
  
  Learn more
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://redux-saga.js.org/" rel="noopener noreferrer"&gt;Sagas Docs&lt;/a&gt;&lt;br&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator" rel="noopener noreferrer"&gt;Generator functions&lt;/a&gt;&lt;/p&gt;

</description>
      <category>redux</category>
      <category>sagas</category>
      <category>react</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
