<?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 A. Sharif on Medium]]></title>
        <description><![CDATA[Stories by A. Sharif on Medium]]></description>
        <link>https://medium.com/@sharifsbeat?source=rss-52e7bcc5db67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fyitFyTCl4VGAYEa.jpg</url>
            <title>Stories by A. Sharif on Medium</title>
            <link>https://medium.com/@sharifsbeat?source=rss-52e7bcc5db67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 15:59:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sharifsbeat/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[Notes on TypeScript: Inferring React PropTypes]]></title>
            <link>https://medium.com/javascript-inside/notes-on-typescript-inferring-react-proptypes-dfb93100523d?source=rss-52e7bcc5db67------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfb93100523d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[A. Sharif]]></dc:creator>
            <pubDate>Sun, 10 Mar 2019 16:52:39 GMT</pubDate>
            <atom:updated>2019-03-10T16:52:39.370Z</atom:updated>
            <content:encoded><![CDATA[<p>These notes should help in better understanding TypeScript and might be helpful when needing to lookup up how to leverage TypeScript in a specific situation. All examples are based on TypeScript 3.2.</p><h3>PropTypes and Inference</h3><p>More often than not we might be working on an existing <strong>React</strong> application, where a team has decided to introduce <strong>TypeScript</strong>. This would also mostly mean that if Components props have to be defined at some point, either defining all at once or gradually. In some cases there also might be existing <em>prop-type</em> definitions. Instead of removing the existing prop-type definitions, we might be able to build a bridge between these prop-types and TypeScript.</p><p>In this part of the “Notes on TypeScript” we will learn how we can leverage TypeScript to infer these component prop-types.</p><p>Before we begin, it’s important to note that the PropTypes type package offers PropTypes.InferProps, which enables to infer the types for an existing prop-type definition like so:</p><pre>const userPropTypes = { <br>  id: PropTypes.number.isRequired, <br>  name: PropTypes.string.isRequired, <br>  active: PropTypes.bool <br>}; </pre><pre>types UserProps = PropTypes.InferProps&lt;typeof userPropTypes&gt;;</pre><p>But let’s take a step back for a minute. What does calling typeof on a PropType definition return?</p><pre>type TypeOfUserProps = typeof userPropTypes;<br><br>/*<br>  type TypeOfUserProps = {<br>    id: PropTypes.Validator&lt;number&gt;;<br>    name: PropTypes.Validator&lt;string&gt;;<br>    active: PropTypes.Requireable&lt;boolean&gt;;<br>  }<br>*/</pre><p>If we take a closer look at userPropTypes, we can see that id and name are required and that the active flag is optional. When inferring these prop-type definitions, we can see that the returned type definition wraps the defined types into either a Validator or Requireable, depending on the fact, that the type has been defined as required or not.</p><p>So internally PropTypes.InferProps differentiates between required and optional types and then creates an intersection between these two groups. We won&#39;t go too deep into the implementation details, but there is a need to find out if a prop-type is required or not. An internal IsOptional type checks if a type is null | undefined and then determines if the type is optional.</p><p>Next, let’s build a small example, to verify if we can transform any prop-type definitions to actual TypeScript types. We have a User component with existing prop-type and default props definitions.</p><pre>const userPropTypes = {<br>  id: PropTypes.number.isRequired,<br>  name: PropTypes.string.isRequired,<br>  active: PropTypes.bool<br>};<br><br>const userDefaultProps = {<br>  name: &quot;Test&quot;<br>};<br><br>const User = (props /*: PropTypes? */) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      id: {props.id}<br>      name: {props.name}<br>      status: {props.active ? &quot;active&quot; : &quot;inactive&quot;}<br>    &lt;/div&gt;<br>  );<br>};<br><br>User.defaultProps = userDefaultProps;</pre><p>How can we infer these userPropTypes and provide the missing types for the User component?</p><p>Our first approach would be to go back to the very first example in this write-up:</p><pre>const userPropTypes = {<br>  id: PropTypes.number.isRequired,<br>  name: PropTypes.string.isRequired,<br>  active: PropTypes.bool<br>};<br><br>types UserProps = PropTypes.InferProps&lt;typeof userPropTypes&gt;;</pre><p>If we verify the example, we can see that this is already working as expected.</p><pre>const User = (props: UserProps) =&gt; {<br>  // ...<br>}<br><br>&lt;User id={1} /&gt; // Works!<br>&lt;User id=&quot;1!&quot; /&gt; // Error! Type &#39;string&#39; is not assignable to type &#39;number&#39;<br>&lt;User /&gt; // Error! Property &#39;id&#39; is missing</pre><p>But we’re not considering any default props, although this should not be the case, they might have a different type. This means we need to extend the existing mechanism to include the inference of default props.<br> There is not very much we need to do:</p><pre>type InferPropTypes&lt;<br>  PropTypes,<br>  DefaultProps = {},<br>  Props = PropTypes.InferProps&lt;PropTypes&gt;<br>&gt; = {<br>  [Key in keyof Props]: Key extends keyof DefaultProps<br>    ? Props[Key] | DefaultProps[Key]<br>    : Props[Key]<br>};</pre><p>If we take a closer look at the above InferPropTypes type, we can notice that we accept the prop-type and default prop types and then infer the provided prop-types. Next, we map over these inferred prop types and check if a key is also defined in the default props. The key extends keyof DefaultProps part helps us to find out if a key actually exists in the default props. If this is the case we return a union of the prop and default prop value type else we only return the prop value type.</p><p>Finally we can use our newly defined InferPropTypes as shown in the next example.</p><pre>type UserProps = <br>  InferPropTypes&lt;typeof userPropTypes, typeof userDefaultProps&gt;;</pre><p>Running our User component again, shows that everything works as expected.</p><pre>const User = (props: UserProps) =&gt; {<br>  // ...<br>}<br><br>&lt;User id={1} /&gt; // Works!<br>&lt;User id=&quot;1!&quot; /&gt; // Error! Type &#39;string&#39; is not assignable to type &#39;number&#39;<br>&lt;User /&gt; // Error! Property &#39;id&#39; is missing</pre><p>We should have a basic understanding of how we can infer existing prop-type definition in a React application when working with TypeScript.</p><p><em>If you have any questions or feedback please leave a comment here or connect via Twitter: </em><a href="https://twitter.com/sharifsbeat"><em>A. Sharif</em></a></p><p><em>Originally published at </em><a href="https://dev.to/busypeoples/notes-on-typescript-inferring-react-proptypes-1g88"><em>dev.to</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfb93100523d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javascript-inside/notes-on-typescript-inferring-react-proptypes-dfb93100523d">Notes on TypeScript: Inferring React PropTypes</a> was originally published in <a href="https://medium.com/javascript-inside">JavaScript Inside</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Do We Need To Solve This Problem?]]></title>
            <link>https://medium.com/@sharifsbeat/what-do-we-need-to-solve-this-problem-79154d07ad49?source=rss-52e7bcc5db67------2</link>
            <guid isPermaLink="false">https://medium.com/p/79154d07ad49</guid>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[agile-development]]></category>
            <dc:creator><![CDATA[A. Sharif]]></dc:creator>
            <pubDate>Fri, 26 Oct 2018 10:39:53 GMT</pubDate>
            <atom:updated>2018-10-26T21:00:10.323Z</atom:updated>
            <content:encoded><![CDATA[<h4>Thinking About The Problem Not The Solution</h4><h4>Introduction</h4><p>When building a product or system there is always another feature to implement. Sometimes it’s very specific in form of a task, describing the required steps in detail, sometimes it’s in form of a story or an epic and might be very vague.<br>Very often we’re already presented with a <strong>solution to a problem</strong>. This leaves a sole developer or development team with figuring out the technical details in best case, only implementing the technical solution at worst.</p><p><strong>But what if we were able to talk about the problem not the solution?</strong><br>Let’s try to get a better understand via an example.</p><h4>Defining The Feature</h4><p>The development team has the following feature in the pipeline:</p><pre><em>As a business analyst I want to be able to export my data, so we can process the data inside Excel.</em></pre><p>This feature is written as a <em>user story</em>, but might come in different shapes and forms. It already provides us with a solution: <em>“export the data”</em>. So we need to export the data as a CSV file f.e.<br>At this point we’re already focused on figuring out how to get the data out of the system. We already have a solution and we need to figure out how to implement this feature on a technical level.</p><p><strong>But what is the actual problem we’re trying to solve?</strong></p><p>The story card doesn’t provide any further information on what happens once the data is exported.</p><ul><li><em>Is there a specific calculation that needs to be run outside the system?</em></li><li><em>Could the solution be provided by the existing product, instead of having to export the data?</em></li></ul><p>These are just hypothetical questions, but once we’re provided with the solution it becomes harder to step back and understand the problem.</p><p>Let’s take the original feature and rewrite it:</p><pre><em>As a business analyst we will need to calculate the median and mean of all recruiting costs on a per month and department basis so we can control the costs during the year.</em></pre><p>Even if this story might sound a little exaggerated, this formulation provides us with a very specific problem now.</p><ul><li><em>Now we might even take another step back and ask what happens with these costs?</em></li><li><em>Do they need to be exported as a PDF or CSV?</em></li><li><em>Are the results imported back into the existing system?</em></li></ul><p>We can <strong><em>keep stepping back and ask further questions</em></strong>, which might help us to better understand the actual underlying problem. The outcome might be that we will solve the actual problem differently, instead of being presented with a solution to part of the problem.</p><h4>Thinking Beyond Features</h4><p>Now you might be trying to argue that this is a process or methodology problem, that the stories need to be done in a way, that leaves room for asking questions. Take a look at at an existing backlog and see how theses stories are formulated and if they help to step out of a specific feature and enable to understand the bigger picture.</p><p>Mostly there is <strong>room to discuss the acceptance criteria </strong>within a feature, as the solution is often already provided directly or indirectly. What mostly happens is that we<strong> shift from thinking about the overall outcome to number of features</strong>. The number of features becomes the driving factor, not the underlying problems these features are set out to solve. Mostly there is a product owner or manager or a product team tasked with ensuring that there is backlog with prioritized features. This also means that the development team is involved later in the process.</p><p>We already have concepts for defining the larger picture, think in terms of <strong>epics</strong> or even <strong>themes</strong>. Themes or epics are vague and help to bound features together, to provide context for these features.</p><p>When we want to think about solving problems, this level of abstraction is the interesting part. But very often the solution is broken into multiple features in form of stories or a different format, and discussed in sprint planing or another development team focused meeting. <strong>We’re interested in an abstraction level that helps us to focus on the problem</strong>.</p><h4>Talking About The Problem</h4><p>What do we gain from talking about the problem?</p><p>There are a number of benefits that we can derive from this approach. It enables a team to have the opportunity to provide valuable feedback early on. It enables everyone involved, especially the team doing the actual work, to get a better understanding of the bigger picture.</p><p><strong><em>What is the problem we are trying to solve and why do we need to solve it?</em></strong></p><p>It creates a platform where we can learn and understand the problem first. Now we can also ask the following question:</p><p><strong><em>What Do We Need To Solve This Problem?</em></strong></p><p>This is different from <em>“Here is the solution, now solve it”</em>. Instead of handing-off a problem from A to B, there is a groundwork for discussing what is actually needed to solve the actual problem.</p><ul><li><strong>It helps to clarify the problem not the solution.</strong></li><li><strong>It helps to derive a solution.</strong></li><li><strong>It opens up room for collaboration.</strong></li><li><strong>It opens up a dialogue.</strong></li><li><strong>It’s not simply outsourcing the problem.</strong></li><li><strong>Is this problem even solvable at given time?</strong></li><li><strong>Is there a different problem that needs to be solved first?</strong></li><li><strong>Can we break up the problem in multiple parts?</strong></li><li><strong>Are the right people involved in solving this problem?</strong></li></ul><h3>A. Sharif on Twitter</h3><p>What do you need to solve the problem?&quot; * It helps to clarify the problem not the solution. * It helps to derive a solution. * It opens up room for collaboration. * It opens up a dialogue. * It&#39;s not simply outsourcing the problem.</p><h4>Summary</h4><p>Very often we’re focused on metrics like number of features or development speed and other quantitive metrics.</p><p><strong>But</strong> <strong>sometimes it makes sense to think about what we are actually trying to solve</strong>.</p><p><strong><em>If you have any questions or feedback please leave a comment here or connect via Twitter: </em></strong><a href="https://twitter.com/sharifsbeat"><strong><em>A. Sharif</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79154d07ad49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Data Validation in JavaScript]]></title>
            <link>https://medium.com/javascript-inside/effective-data-validation-in-javascript-5c2f3e75249e?source=rss-52e7bcc5db67------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c2f3e75249e</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[A. Sharif]]></dc:creator>
            <pubDate>Sun, 21 Oct 2018 11:12:59 GMT</pubDate>
            <atom:updated>2018-10-21T16:46:51.016Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>Most applications will need to <strong>validate data</strong> at some point. This data might be provided by an external service or via user interaction or input. This is nothing special and in most cases we might have a <em>helper</em> library or <em>common</em> functions for validating that data.</p><p>This write-up is intended to provide another way of validating data.</p><h4>Basic Validation Functions</h4><p>Let’s take a look at the following example, where we want to guarantee that the provided user name has a minimum length of 8 characters:</p><pre>const <strong>checkUserName</strong> = data =&gt;<br>  data &amp;&amp; data.length &gt; 8 <br>    ? data <br>    : “Minimum of 8 characters required!”;</pre><pre>// validate the username<br><strong>checkUserName</strong>(“User A”); // =&gt; “Minimum 8 characters required!”</pre><p>This validation function already works as expected and returns the appropriate <em>error message</em> if the provided input is invalid. Now let’s take a look at another situation, where we might want to define a different message.</p><pre>const <strong>checkUserName</strong> = (data, errorMsg) =&gt;<br>  data &amp;&amp; data.length &gt; 8 <br>    ? data <br>    : errorMsg;</pre><pre>// validate the username<br><strong>checkUserName</strong>(“User A”, “Minimum of 8 characters is required!”); <br>// =&gt; “Minimum of 8 characters is required!”</pre><p>Again, we can dynamically define the error message when needed, but we also might want to be able to define the validation function itself. This would leave our <em>checkUserName</em> function to have no concept of what a user name actually is.</p><pre>const <strong>runValidation</strong> = (data, validation, errorMsg) =&gt;<br>  validation(data) ? data : errorMsg;</pre><pre>// validate the username<br><strong>runValidation</strong>(<br>  “User A”,<br>  data =&gt; data &amp;&amp; data.length &gt; 8,<br>  “Minimum 8 of characters required!”<br>); // =&gt; “Minimum of 8 characters required!”</pre><p>We renamed our <em>checkUserName</em> function to <em>runValidation</em>, as this function is independent of any context. It expects the data, a validation function and an error message.</p><p>Taking a closer look at <em>runValidation</em>, we might notice that if we wanted to run <em>checkUserName</em> with different data, we would have to redefine the validation function and error message every time as well.<br>But we’re mainly interested in defining the specific validation function and error message once, and then running that function with different data.</p><p>Our next attempt is to enable providing data as against a defined validation function.</p><pre>const <strong>runValidation</strong> = (validation, errorMsg) =&gt; data =&gt;<br>  validation(data) ? data : errorMsg;</pre><pre>// validate the username<br>const <strong>validateUserName</strong> = <strong>runValidation</strong>(<br>  data =&gt; data &amp;&amp; data.length &gt; 8,<br>  “Minimum 8 characters required!”<br>);</pre><pre><strong>validateUserName</strong>(“User A”); // =&gt; “Minimum 8 characters required!”</pre><p>This approach ensures that the validation function can be defined once and run multiple times with different inputs. If you recall, we’re calling <em>validateUserName</em> with just the data, just like in the very first example now.</p><p>Our current implementation ensures validation functions to be built dynamically and this is already quite useful. But in the next section, we will see how we can improve this concept and the overall convenience.</p><h4>Error Handling</h4><p>Now that we have a better understanding of how to build dynamic validations, let’s take a look at how we would work with the results of said validations.</p><p>We would probably assign the result to a value and depending on the expected outcome do something with the result. f.e. display an error message or perform some other actions. Let’s see how we might approach this for the <em>validateUserName</em> case.</p><pre>const <strong>result</strong> = <strong>validateUserName</strong>(“User A”);</pre><p>In the example above we would get back an error message. So we would either display an error message or the actual user name. But we can see a problem here, as <em>we can’t distinguish between the two result types</em>. We can’t highlight the error, as the result doesn’t provide any further information. We need to refactor our <em>runValidation</em> to return true if the provided data is valid.</p><pre>const <strong>runValidation</strong> = (validation, errorMsg) =&gt; data =&gt;<br>  validation(data) ? true : errorMsg;</pre><pre>// validate the username<br>const <strong>validateUserName</strong> = <strong>runValidation</strong>(<br>  data =&gt; data &amp;&amp; data.length &gt; 8,<br>  “Minimum 8 characters required!”<br>);</pre><pre><strong>validateUserName</strong>(“User A”); // =&gt; “Minimum 8 characters required!”</pre><p>By changing our function, we are able to distinguish <strong>between an error and a successful</strong> validation.</p><pre>const <strong>result</strong> = <strong>validateUserName</strong>(“User A”);</pre><pre>if (result === true) {<br> // work with the data<br>} else {<br> // display an error message<br>}</pre><p>We still need to do a lot of work and we might even need to handle multiple validations and return all errors at once. This would mean we have to collect these results and then combine them. We can improve the overall handling.</p><h4>Improved Validation Constructors</h4><p>In the following section we will see how we might be able to add more convenience when working with the validation results.<br>What if we were able to build a pipeline, not needing to manually handle the case, but define what should happen when the validation is run?</p><p>Let’s see how this might look like.</p><pre>const <strong>createUserName</strong> = <strong>createValidation</strong>(<br>  a =&gt; a &amp;&amp; a.length &gt; 6,<br>  “Minimum of 7 characters required”<br>);</pre><p>This looks very similar to the <em>validateUserName</em> function, but this function states that we are creating a user name in this case. To better understand why this might make sense let’s take a look at the following example.</p><pre>const <strong>createUserName</strong> = <strong>createValidation</strong>(<br>  a =&gt; a &amp;&amp; a.length &gt; 6, <br>  “Minimum of 7 characters required”<br>);</pre><pre><strong>createUserName</strong>(“User A”).cata({<br>  error: e =&gt; e // error message,<br>  success: data =&gt; data // the valid data<br>});</pre><p>We are providing a quasi constructor function. All we need to do is pass in a <strong><em>branching</em></strong> function, telling <em>createUserName</em> how to handle each case.<br>Now that we have a better understanding of the benefits, let’s see how we might implement the createValidation function.</p><pre>const <strong>createValidation</strong> = (fn, errorMsg, type) =&gt; data =&gt; {<br>  const result = fn(data);<br>  return {<br>    cata: branch =&gt;<br>      result <br>        ? branch.right(result, type) <br>        : branch.left(errorMsg, type),<br>    type<br>  };<br>};</pre><p>The function itself needs the <em>validation function</em> and optionally an <em>error</em> <em>message</em> and a <em>type</em>. The type might be useful if we want to distinguish between as well as do something depending on that type. Type can also be replaced with something else that might provide context. The actual implementation might vary, depending on the specific case, but the important aspect is that result is an object enabling user land to define how to handle the result outcome via the <strong><em>cata</em></strong> function.</p><h4>Example: Form Validation</h4><p>To see why this approach is useful, let’s take a look at form validating.<br>We might have a form, where we might provide a user name, a phone and an email address.</p><pre>const <strong>EMAIL</strong> = “EMAIL”;<br>const <strong>PHONE</strong> = “PHONE”;</pre><pre>const <strong>createUserName</strong> = <strong>createValidation</strong>(<br>  a =&gt; a &amp;&amp; a.length &gt; 5, <br>  “Minimum of 6 characters required”<br>);</pre><pre>const <strong>createEmail</strong> = <strong>createValidation</strong>(<br>  a =&gt; a &amp;&amp; a.length &gt; 6,<br>  “Minimum of 7 characters required”,<br>  EMAIL<br>);</pre><pre>const <strong>createPhone</strong> = <strong>createValidation</strong>(<br>  a =&gt; a &amp;&amp; a.length &gt; 7,<br>  “Minimum of 8 characters required”,<br>  PHONE<br>);</pre><p>Ignore the naive validation functions, these depend on the specific case you’re trying to validate. But more interestingly we can <strong>map the results of a form to the different <em>validation constructors</em></strong>.</p><pre>const <strong>formValues</strong> = {<br>  email: createEmail(“foo@”),<br>  phone: createPhone(“987654321”),<br>  userName: createUserName(“UserA”)<br>};</pre><p>What’s missing is a custom validation function, that expects the form values and returns an object that maps the field names to the result. The implementation is up to user land, but the following example should highlight the fact, that we can implement the mapping as needed.</p><pre>const <strong>validateFormValues</strong> = values =&gt;<br>  Object.keys(values).map(key =&gt; ({<br>    [key]: values[key].cata({<br>      left: e =&gt; e,<br>      right: a =&gt; a<br>    })<br>  })<br>);</pre><p>Now we can call our newly created <em>validateFormValues</em> function with the form values and get back an array of objects containing a result for each field value.</p><pre>const <strong>errors</strong> = <strong>validateFormValues</strong>(formValues);</pre><p>The result will have the following structure:</p><pre>[<br>  { email: “Minimum of 7 characters required” }, <br>  { phone: true }, <br>  { userName: “Minimum of 6 character required” }<br>]</pre><p>The result can be a single object or an array of error messages etc. This depends on our specific case and can be implemented as needed via defining a specific mapping function.</p><p><em>Checkout the demo</em>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fr5lr3qjl3q%3Fexpanddevtools%3D1%26hidenavigation%3D1&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fr5lr3qjl3q%3Fexpanddevtools%3D1%26hidenavigation%3D1&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fr5lr3qjl3q%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/783b10ae7fcd2bbab7f33be2f86eb030/href">https://medium.com/media/783b10ae7fcd2bbab7f33be2f86eb030/href</a></iframe><h4>Example: Safely Accessing Deeply Nested Data</h4><p>We will take a look at one final example, just to clarify the benefits of this way of validating data. Our <em>createValidation</em> can be used to create a function that can safely access deeply nested data for example. There are better and more efficient ways to handle this, but it’s useful for demonstrating that we can use this approach in different situations.</p><pre>const <strong>getValue</strong> = <strong>createValidation</strong>(a =&gt; {<br>  try {<br>    return a();<br>  } catch (e) {<br>    return false;<br>  }<br>});</pre><pre>const <strong>safelyAccessDeepNestedData</strong> = (data, defaultValue) =&gt; {<br>  return getValue(data).cata({<br>    left: () =&gt; defaultValue,<br>    right: a =&gt; a<br>  });<br>};</pre><p>This enables us to access a deep nested value.</p><pre>const <strong>a</strong> = 1;<br>const <strong>b</strong> = { c: { d: 2 } };</pre><pre><strong>safelyAccessDeepNestedData</strong>(() =&gt; a.b.c); // =&gt; undefined<br><strong>safelyAccessDeepNestedData</strong>(() =&gt; b.c.d); // =&gt; 2</pre><p><em>Checkout the demo.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F357o4nw31%3Fexpanddevtools%3D1%26hidenavigation%3D1&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F357o4nw31%3Fexpanddevtools%3D1%26hidenavigation%3D1&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F357o4nw31%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/df40177fb5c180dbca68b53e3652de08/href">https://medium.com/media/df40177fb5c180dbca68b53e3652de08/href</a></iframe><h4>Summary</h4><p>This approach might be useful in situations where we want to control the outcome of the validation result. We might even use this function to validate data inside a React component f.e., either rendering an error message or nothing depending on the validation result.</p><p><em>If there is interest, there is a possibility of a follow-up to this write-up showing how to leverage these ideas directly in React f.e.</em></p><p><strong><em>If you have any questions or feedback please leave a comment here or connect via Twitter: </em></strong><a href="https://twitter.com/sharifsbeat"><strong><em>A. Sharif</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c2f3e75249e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javascript-inside/effective-data-validation-in-javascript-5c2f3e75249e">Effective Data Validation in JavaScript</a> was originally published in <a href="https://medium.com/javascript-inside">JavaScript Inside</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Your React Views Explicit!]]></title>
            <link>https://medium.com/javascript-inside/make-your-react-views-explicit-7813c626ae9d?source=rss-52e7bcc5db67------2</link>
            <guid isPermaLink="false">https://medium.com/p/7813c626ae9d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[A. Sharif]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 10:37:19 GMT</pubDate>
            <atom:updated>2018-08-11T10:37:59.285Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>When building <strong>React</strong> components or components in general we sometimes need to consider that a certain property should or should not be displayed. We mostly model our component data to reflect this situation by using a boolean flag f.e.</p><p>Sometimes we also use a defined set of values and sometimes we make our input data optional. All these approaches should enable the component consumer to be able to define if or what should be displayed.</p><p>This all sounds sensible at first look, but we will try to understand where problems might arise and how we can model our data differently to handle these type of situations.</p><p><strong>Note:</strong> <em>We are going to use </em><strong><em>PropTypes</em></strong><em> to define the data shape, but this can<br>also be achieved via </em><strong><em>Flow</em></strong><em> or </em><strong><em>TypeScript</em></strong><em> type definitions.</em></p><h4>Limitations</h4><p>Before we try to better understand where problems might arise, let’s summarise possible ways to enable to define if and what should be rendered to the screen.</p><ul><li><strong>Boolean flag</strong>, i.e. &lt;BlogPost showTitle /&gt;</li><li><strong>Enums</strong>, i.e. &lt;BlogPost status=&quot;draft&quot; /&gt;</li><li><strong>Optional</strong>, i.e. &lt;div&gt;{title &amp;&amp; &lt;Title content={title}/&gt;}&lt;/div&gt;</li></ul><p>This all looks sensible when we look at it from an isolated perspective, we can indicate what we want to be displayed.</p><p>But what happens when our component needs more than a boolean flag or the boolean flag needs to be refactored to an enum?<br>What if we have two inputs like <em>status</em> and <em>id</em>, but an <em>id</em> shouldn’t be displayed when the <em>status</em> is <em>new</em>? Now we need to keep track of multiple inputs.</p><p>The best thing we can do, is try to build a more than trivial example, to fully<br>understand the implications. For example we might be writing a BlogPostInfo component that, as the name implies, should display any relevant blog post information like <em>status</em>, <em>creation</em> and <em>published</em> <em>date</em> or the number of <em>views</em>.</p><p>So there is some information we need to keep in sync when rendering the information. First off, let’s take a look at all the possible states:</p><pre>const PostStatus = {<br>  New: “New”,<br>  Draft: “Draft”,<br>  Review: “Review”,<br>  Published: “Published”,<br>  Removed: “Removed”<br>}</pre><p>We can see five possible state representations and each containing state specific information . For example, a blog post can have a creation but no published date. This implies that we need to consider these constraints when rendering the information.</p><p>Let’ assume have a basic understanding of what our BlogPostInfo should be able to display.</p><pre><br>BlogPostInfo.propTypes = {<br>  title: propTypes.string.isRequired,<br>  status: propTypes.oneOf(Object.keys(PostStatus)).isRequired,<br>  id: propTypes.number,<br>  createdDate: propTypes.object,<br>  publishedDate: propTypes.object,<br>  reviewedDate: propTypes.object,<br>  removedDate: propTypes.object,<br>  views: propTypes.number <br>}</pre><p>Every post has a <em>title </em>and<em> status</em>, which means we can make the <em>title</em> and <em>status</em> property <strong>required. </strong>These two properties are shared by all posts but everything else depends on the status.</p><p>This means we need to cover all cases via <strong><em>JSX</em></strong> and check what is needed to ensure that everything is in sync. We do this to avoid making incompatible representations, like f.e. rendering a published date when in draft status.</p><p>It’s time to see how we might our BlogPostInfo component.</p><pre>const BlogPostInfo = ({<br>  title,<br>  status,<br>  id,<br>  createdDate,<br>  publishedDate,<br>  reviewedDate,<br>  removedDate,<br>  views<br>}) =&gt; (<br>  &lt;div&gt;<br>  &lt;h2&gt;{title}&lt;/h2&gt;<br>  &lt;div&gt;status: {status}&lt;/div&gt;<br>  &lt;div&gt;<br>    {status === “New” <br>      ? “Save this post.” <br>      : `Update post with id ${id}.`<br>    }<br>  &lt;/div&gt;<br>  {createdDate &amp;&amp; &lt;div&gt;created at: {formatDate(createdDate)}&lt;/div&gt;}<br>  {reviewedDate &amp;&amp; <br>    &lt;div&gt;reviewed at: {formatDate(reviewedDate)}&lt;/div&gt;}<br>  {publishedDate &amp;&amp; <br>    &lt;div&gt;published at: {formatDate(publishedDate)}&lt;/div&gt;}<br>  {removedDate &amp;&amp; &lt;div&gt;removed at: {formatDate(removedDate)}&lt;/div&gt;}<br>  {views !== undefined &amp;&amp; &lt;div&gt;view count: {views}&lt;/div&gt;}<br> &lt;/div&gt;<br>)</pre><p>It might seem more confusing that it actually is, but we need to do multiple checks here, as we can’t rely on too much from what is being passed into the component. <strong><em>There are a couple of possible scenarios here, were we might easily render an incorrect representation.</em></strong> <strong>The props don’t give us enough information</strong> as they are mostly <strong>optional</strong>.</p><p>How can a component consumer represent incorrect information?</p><p>Let’s take a look at a couple of possible scenarios:</p><p><em>The post is in status draft, but we don’t pass in any id.</em></p><pre>&lt;BlogPostInfo<br>  title=”This post is in a draft status! (but it’s missing an id!)”<br>  status={PostStatus.Draft}<br>  createdDate={new Date(“2018–07–01 12:45”)}<br>/&gt;</pre><p><em>The post might be in review status but we only provide a createdDate but no reviewDate.</em></p><pre>&lt;BlogPostInfo<br>  title=”This post is in a review status! (but no review date!)”<br>  status={PostStatus.Review}<br>  createdDate={new Date(“2018–07–01 12:45”)}<br>  id={123}<br>/&gt;</pre><p><em>Another possible scenario is that we don’t provide the view count for a published post, as view count is optional.</em></p><pre>&lt;BlogPostInfo<br>  title=”This post is in a published status! (view is missing!)”<br>  status={PostStatus.Published}<br>  createdDate={new Date(“2018–07–01 12:45”)}<br>  reviewedDate={new Date(“2018–07–02 17:02”)}<br>  publishedDate={new Date(“2018–07–03 10:20”)}<br>  id={123}<br>/&gt;</pre><p><em>One final example.</em></p><pre>&lt;BlogPostInfo<br>  title=”This post has removed status (but wrong status no views!)”<br>  status={PostStatus.Published}<br>  createdDate={new Date(“2018–07–01 12:45”)}<br>  reviewedDate={new Date(“2018–07–02 17:02”)}<br>  publishedDate={new Date(“2018–07–03 10:20”)}<br>  removedDate={new Date(“2018–07–09 19:17”)}<br>  id={123}<br>/&gt;</pre><p>As we can see from the above examples, we can quickly come up with a number of possible scenarios where we have<strong> incorrect representation of our actual data</strong>.</p><h4>Being Explicit</h4><p>In the previous section we were able to demonstrate why using optional props, boolean flags or enums can lead to incorrect UI representations.<br>Now that we have a solid understanding of the scenario, let’s <strong>refactor our original components to multiple components</strong>, each <strong>representing an explicit state</strong>.</p><p>Let’s choose two possible scenarios an implement explicit representations.<br>First, let’s choose the initial state, the <strong>new</strong> state.</p><pre>const BlogPostNew = ({ title }) =&gt; (<br>  &lt;div&gt;<br>    &lt;h2&gt;{title}&lt;/h2&gt;<br>    &lt;div&gt;status: New&lt;/div&gt;<br>    &lt;div&gt;Save this post.&lt;/div&gt;<br>  &lt;/div&gt;<br>)</pre><pre>BlogPostNew.propTypes = {<br>  title: propTypes.string.isRequired<br>}</pre><p>This looks very minimal, but interestingly this is all we need to represent our<br>initial state. <strong>We don’t even need the <em>status</em> property</strong>, because we already know exactly in which state our data is. We delegate the decision when the New state is rendered to a top level component. All we need is a <em>title</em> property, which is required and has to be provided.</p><p>To clarify our explicit approach, let’s also build a component that represents a<br><strong>published</strong> state.</p><pre>const BlogPostPublished = ({ title, id, …props }) =&gt; (<br>  &lt;div&gt;<br>    &lt;h2&gt;{title}&lt;/h2&gt;<br>    &lt;div&gt;status: Published&lt;/div&gt;<br>    &lt;div&gt;Update post with id {id}.&lt;/div&gt;<br>    &lt;div&gt;created at: {formatDate(createdDate)}&lt;/div&gt;<br>    &lt;div&gt;reviewed at: {formatDate(reviewedDate)}&lt;/div&gt;<br>    &lt;div&gt;published at: {formatDate(publishedDate)}&lt;/div&gt;<br>    &lt;div&gt;view count: {views}&lt;/div&gt;<br>  &lt;/div&gt;<br>)</pre><pre>BlogPostPublished.propTypes = {<br>  title: propTypes.string.isRequired,<br>  id: propTypes.number.isRequired,<br>  createdDate: propTypes.object.isRequired,<br>  reviewedDate: propTypes.object.isRequired,<br>  publishedDate: propTypes.object.isRequired,<br>  views: propTypes.number.isRequired<br>}</pre><p>There is definitely more going on as compared to the previous example, but again we can observe that <strong>every property is required</strong>. There are <strong>no optional props</strong>, also <strong>no state enum</strong>. We exactly know, that we are in the context of a published post.</p><p>The component consumer has to provide all necessary data, which means we can always represent the correct state information.</p><p>If you recall our previous examples, we can make these states explicit now.</p><pre>&lt;BlogPostReview<br>  title=”Explicit Review Post! (No missing reviewDate)”<br>  id={123}<br>  createdDate={new Date(“2018–07–01 12:45”)}<br>  reviewedDate={new Date(“2018–07–02 17:02”)}<br>/&gt;</pre><p>The <strong>removed</strong> state that had an incorrect state and missing view count can now be explicitly defined.</p><pre>&lt;BlogPostRemoved<br>  title=”Explicit removed state!(no incorrect state has view count)”<br>  createdDate={new Date(“2018–07–01 12:45”)}<br>  reviewedDate={new Date(“2018–07–02 17:02”)}<br>  publishedDate={new Date(“2018–07–03 10:20”)}<br>  removedDate={new Date(“2018–07–09 19:17”)}<br>  id={123}<br>  views={4567}<br>/&gt;</pre><h4>Explicit State Transitions</h4><p>One positive effect we gain from taking the explicit route is that we can also<br><strong>be explicit about our state transitions </strong>now.<strong> </strong>For example we can define a <em>publish</em> function that only accepts a post in <strong>draft</strong> or <strong>review</strong> status and otherwise throws an error.</p><p>Taking this route means we need to model our data to represent the possible states. The following approach is a simplified approach, but should suffice for better understanding what benefits we can derive. Also we can use a library like <strong>daggy</strong> or a full fledged approach like <strong>xstate </strong>to leverage the benefits.</p><pre>function publish(post) {<br>  if (post.type === &#39;Draft&#39;) {<br>    return { <br>      …post.data, <br>      reviewedDate: new Date(), <br>      publishedDate: new Date(),<br>      views: 0<br>    }<br>  }</pre><pre>  if (post.type === &#39;Review&#39;) {<br>    return { <br>      …post.data, <br>      publishedDate: new Date(),<br>      views: 0<br>    }<br>  }<br>  // throw an error...<br>}</pre><p>Finally, here is a demo with showing the explicit blog post state.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fn9wz7zrxrp&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fn9wz7zrxrp&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fn9wz7zrxrp%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d782672f90f0b41a759a783dcfb691cc/href">https://medium.com/media/d782672f90f0b41a759a783dcfb691cc/href</a></iframe><p>Hopefully this post was useful. It’s also important to note, that making your views explicit should be well thought through. First check, if this will solve the actual problem and then focus on how to model these explicit states.</p><p><strong><em>If you have any questions or feedback please connect via Twitter: </em></strong><a href="https://twitter.com/sharifsbeat"><strong><em>A. Sharif</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7813c626ae9d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javascript-inside/make-your-react-views-explicit-7813c626ae9d">Make Your React Views Explicit!</a> was originally published in <a href="https://medium.com/javascript-inside">JavaScript Inside</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transforming Elements In React]]></title>
            <link>https://medium.com/javascript-inside/transforming-elements-in-react-8e411c0f1bba?source=rss-52e7bcc5db67------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e411c0f1bba</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[A. Sharif]]></dc:creator>
            <pubDate>Mon, 02 Jul 2018 09:02:21 GMT</pubDate>
            <atom:updated>2018-07-02T09:02:21.376Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Transforming elements can be interesting if you’re a library author, but can also be very valuable when writing components to abstract behaviour in your existing code base.</p><p>To get a better understanding, we will walkthrough the most important React Top Level API transformation functionalities. React offers a couple of helper functions that we can leverage when for creating and adapting elements, further information is available via the <a href="https://reactjs.org/docs/react-api.html">official React documentation</a>.</p><p>Let’s take a closer look at what we can take-away in the first section and then build a component that leverages the newly learnt features.</p><h3>Basics</h3><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;</pre><p>render is our main function, which we will use to render all our examples.</p><pre>const render = Component =&gt;<br>  ReactDOM.render(Component, document.getElementById(&quot;root&quot;));</pre><p>Let’s build a Title element and a stateless component called App.</p><pre>const Title = &lt;h1&gt;Transforming Elements&lt;/h1&gt;;<br>const App = () =&gt; &lt;div&gt;{Title}&lt;/div&gt;;</pre><pre>console.log(&quot;Title is valid?&quot;, React.isValidElement(Title)); <br>// =&gt; true<br>console.log(&quot;App is valid?&quot;, React.isValidElement(App)); <br>// =&gt; false</pre><p>With the help of isValidElement we can check, as the name already implies, if the element is a React element or not. The following checks validate that Title is an actual React element, while App itself is not, as it&#39;s a function. When calling App we get a valid element back, which can be verified via the next isValidElement check.</p><pre>console.log(&quot;&lt;App /&gt; is valid?&quot;, React.isValidElement(&lt;App /&gt;)); <br>// =&gt; true</pre><p>What could be a useful case for needing these checks? For example if we need to know if we have to create or clone an element. Which brings us to the next interesting feature, createElement and respectively cloneElement.</p><p>Even if you’re wondering what createElement is, you&#39;ve actually already used this function, even if unknowingly. When we wrote</p><p>&lt;h1&gt;Transforming Elements&lt;/h1&gt;</p><p>what actually happened was that this JSX definition was converted to:</p><pre>React.createElement(&quot;h1&quot;, {}, &quot;Transforming Elements&quot;)</pre><p>Let’s build the exact definition and render it to the screen.</p><pre>const TitleH1 = React.createElement(<br>  &quot;h1&quot;,<br>  null,<br>  &quot;Transforming Elements&quot;<br>);</pre><pre>render(TitleH1);</pre><p>We can already verify that this is working as expected. Let’s take a closer look at the createElement arguments.</p><pre>React.createElement(type, [props], [...children])</pre><p>As we can see from the above definition, we need a valid <em>type</em>, but what happens when we try to invoke it with an invalid element?</p><pre>const TitleTest = React.createElement(<br>  &quot;test&quot;,<br>  null,<br>  &quot;Transforming Elements&quot;<br>);</pre><pre>render(TitleTest);</pre><p>A console warning is logged:</p><pre>Warning: The tag &lt;test&gt; is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.</pre><p>So React can tell when we’re passing in an invalid node type. But the warning also reveils another interesting information:</p><pre>If you meant to render a React component, start its name with an uppercase letter.</pre><p>This message indicates that we can pass in a React component as the first argument. Let’s try this out.</p><pre>const TitleSubtitle = ({ children, title }) =&gt; (<br>  &lt;div&gt;<br>    &lt;h1&gt;{title}&lt;/h1&gt;<br>    &lt;h2&gt;{children}&lt;/h2&gt;<br>  &lt;/div&gt;<br>);</pre><pre>const SubtitleComponent = React.createElement(<br>  TitleSubtitle,<br>  null,<br>  &quot;Rendering more content&quot;<br>);</pre><pre>render(TitleSubtitleComponent);</pre><p>We can see that the children content is rendered into the H2 tag, but how can we define the title? If you recall, createElement accepts props optionally as a second argument. So our next step is to define the title we want displayed.</p><pre>const TitleSubtitleComponent = React.createElement(<br>  TitleSubtitle,<br>  { title: &quot;Transforming Elements&quot; },<br>  &quot;Rendering more content&quot;<br>);</pre><pre>render(TitleSubtitleComponent);</pre><p>We can verify that this works. Now that we have a basic understanding of what happens when we use JSX, let’s take a look at another useful React top level API feature.</p><p>cloneElement has the following definition:</p><pre>React.cloneElement(element, [props], [...children])</pre><p>At first glance, this looks very similar to the previously explained createElement, with one important distinction, it expects a valid React element. So, let&#39;s go back to isValidElement again and verify that our current component actually works as expected.</p><pre>console.log(&quot;TitleSubtitleComponent is valid?&quot;, React.isValidElement(TitleSubtitleComponent)); // =&gt; true</pre><p>We already know that we have a valid element, otherwise we wouldn’t have been able to previously render the component, but also gave us another opportunity to run isValidElement one more time.</p><p>Next let’s assume we have a third value we want to display inside our component.</p><pre>const TitleSubtitleInfo = ({ children, title, info }) =&gt; (<br>  &lt;div&gt;<br>    &lt;h1&gt;{title}&lt;/h1&gt;<br>    &lt;h2&gt;{children}&lt;/h2&gt;<br>    &lt;h4&gt;{info}&lt;/h4&gt;<br>  &lt;/div&gt;<br>);</pre><pre>const TitleSubtitleNoInfoComponent = React.createElement(<br>  TitleSubtitleInfo,<br>  { title: &quot;Transforming Elements&quot; },<br>  &quot;Rendering more content&quot;<br>);</pre><p>How can we add info to our props? Let&#39;s clone our existing TitleSubtitleNoInfoComponent component and pass in info via props.</p><pre>const TitleSubtitleInfoComponent = React.cloneElement(<br>  TitleSubtitleNoInfoComponent,<br>  { info: &quot;Additional Info&quot; }<br>);</pre><pre>render(TitleSubtitleInfoComponent);</pre><p>As we can see, we are able to display the additional info. cloneElement gives us the capability to extend a React element with additional props when needed. It&#39;s important to note that we can achieve the same via:</p><pre>// <a href="https://reactjs.org/docs/react-api.html#cloneelement">https://reactjs.org/docs/react-api.html#cloneelement</a></pre><pre>&lt;element.type {...element.props} {...props}&gt;{children}&lt;/element.type&gt;</pre><p>This also means, we can override any children, via defining the third argument. We will keep this in mind, when building an actual example in the next section.</p><p>Aside from creating and transforming single elements, the React API also exposes React.Children, a collection of utility functions for working with children elements.</p><p>What if we need to verify that we only have a single child element? This is where only comes handy.</p><pre>const { count, forEach, map, only, toArray } = React.Children;</pre><pre>// helper class<br>class Verify extends React.Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h2&gt;Verify: {this.props.title}&lt;/h2&gt;<br>        Result:<br>        &lt;div&gt;{this.props.verify(this.props.children)}&lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>If we pass in a collection or a non React Element, only will throw an error. This can help us to ensure that we actually only have single Element, which can be useful when creating a library and needing to enforce this constraint.</p><pre>render(<br>  &lt;Verify title=&quot;Single Element&quot; verify={c =&gt; (only(c) ? &quot;True&quot; : &quot;False&quot;)}&gt;<br>    &lt;div&gt;Single React Element&lt;/div&gt;<br>  &lt;/Verify&gt;<br>);</pre><p>There might be a need to count the number of children, which we can do via the count function. A simple length check might fail because we can&#39;t guarantee that children are of type array.</p><pre>const Element = ({ id }) =&gt; &lt;div key={id}&gt;Element {id}&lt;/div&gt;;</pre><pre>render(<br>  &lt;Verify<br>    title=&quot;Should contain 3 Elements&quot;<br>    verify={c =&gt; (count(c) === 3 ? &quot;True&quot; : &quot;False&quot;)}<br>  &gt;<br>    &lt;Element id=&quot;1&quot; /&gt;<br>    &lt;Element id=&quot;2&quot; /&gt;<br>    &lt;Element id=&quot;3&quot; /&gt;<br>  &lt;/Verify&gt;<br>);</pre><p>Further more React.Children offers two different ways to iterate over a children collection: map and forEach.</p><p>They function just as the Array based map and forEach. map returns a new collection, except in cases where children is null or undefined (returning null or respectively undefined) while forEach is the imperative counterpart.</p><p>To extend on our existing example, let’s try to an additional property by mapping over a child collection and adding a new prop name.</p><pre>const ElementAdditionalProp = ({ id, name }) =&gt; (<br>  &lt;div key={id} id={id}&gt;<br>    Element:{name} {id}<br>  &lt;/div&gt;<br>);</pre><p>In the following example we map over the collection and clone every single element and merge the new prop name with the existing props.</p><pre>render(<br>  &lt;Verify<br>    title=&quot;Map Multiple Elements&quot;<br>    verify={c =&gt; map(c, El =&gt; React.cloneElement(El, { name: &quot;Mapped&quot; }))}<br>  &gt;<br>    &lt;ElementAdditionalProp id=&quot;1&quot; /&gt;<br>    &lt;ElementAdditionalProp id=&quot;2&quot; /&gt;<br>    &lt;ElementAdditionalProp id=&quot;3&quot; /&gt;<br>  &lt;/Verify&gt;<br>);</pre><p>Here is the same example like the previous one, with one difference, we use forEach to achieve the same outcome.</p><pre>render(<br>  &lt;Verify<br>    title=&quot;ForEach Mulitple Elements&quot;<br>    verify={c =&gt; {<br>      let elements = [];<br>      forEach(c, El =&gt;<br>        elements.push(React.cloneElement(El, { name: &quot;ForEach&quot; }))<br>      );<br>      return elements;<br>    }}<br>  &gt;<br>    &lt;ElementAdditionalProp id=&quot;1&quot; key=&quot;1&quot; /&gt;<br>    &lt;ElementAdditionalProp id=&quot;2&quot; key=&quot;2&quot; /&gt;<br>    &lt;ElementAdditionalProp id=&quot;3&quot; key=&quot;3&quot; /&gt;<br>  &lt;/Verify&gt;<br>);</pre><p>There will be situations where we might need to access to the actual children array instead of the opaque data structure. toArray enables us to convert the actual child list to a flatted list.</p><pre>render(<br>  &lt;Verify<br>    title=&quot;toArray and filter Multiple Elements&quot;<br>    verify={c =&gt; {<br>      const elements = toArray(c);<br>      return elements.filter(El =&gt; El.props.points &gt; 100);<br>    }}<br>  &gt;<br>    &lt;ElementAdditionalProp id=&quot;1&quot; key=&quot;1&quot; points={100} /&gt;<br>    &lt;ElementAdditionalProp id=&quot;2&quot; key=&quot;2&quot; points={200} /&gt;<br>    &lt;ElementAdditionalProp id=&quot;3&quot; key=&quot;3&quot; points={300} /&gt;<br>  &lt;/Verify&gt;<br>);</pre><h3>Example</h3><p>Now that we have a basic understanding of how to create and transform elements and which utilities are available for helping us with these transformations, let’s build something useful.</p><p>We will build a &lt;Pipe /&gt; component for composing multiple components that all use a render-callback approach. A render-callback is leveraged by the following components for example, where children is a function.</p><pre>class AddX extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { x: this.props.initX || 0 };<br>  }<br>  render() {<br>    const { initX, ...props } = this.props;<br>    return this.props.children({ ...this.state, ...props });<br>  }<br>}</pre><pre>class AddY extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { y: this.props.initY || 0 };<br>  }<br>  render() {<br>    const { initY, ...props } = this.props;<br>    return this.props.children({ ...this.state, ...props });<br>  }<br>}</pre><p>Let’s quickly see how this might work composing multiple of these components.</p><pre>const ComposedRenderCallbacks = () =&gt; (<br>  &lt;AddX initX={10} additionalProp=&quot;Testing Composition&quot;&gt;<br>    {props =&gt; (<br>      &lt;AddY {...props} initY={20}&gt;<br>        {({ x, y, additionalProp }) =&gt; (<br>          &lt;div&gt;<br>            &lt;h4&gt;Additional Prop: {additionalProp}&lt;/h4&gt;<br>            X: {x}<br>            &lt;br /&gt;<br>            Y: {y}<br>          &lt;/div&gt;<br>        )}<br>      &lt;/AddY&gt;<br>    )}<br>  &lt;/AddX&gt;<br>);</pre><pre>render(&lt;ComposedRenderCallbacks /&gt;);</pre><p>We can verify that composition works by nesting components. Our component should enable to compose multiple components similar to a regular pipe function without having to keep nesting. So our high level goal is to offer a pipe(comp1, comp2, comp3, ..., viewComp) via JSX.</p><p>Let’s think about how this might look in JSX. Here is a possible outcome:</p><pre>&lt;Pipe info=&quot;Pipe Function Rendering X and Y&quot;&gt;<br>  &lt;AddX initX={10} /&gt;<br>  &lt;AddY initY={20} /&gt;<br>  {({ x, y, info }) =&gt; (<br>    &lt;div&gt;<br>      &lt;h4&gt;Info: {info}&lt;/h4&gt;<br>      X: {x}<br>      &lt;br /&gt;<br>      Y: {y}<br>    &lt;/div&gt;<br>  )}<br>&lt;/Pipe&gt;</pre><p>Just by looking at the above example, we can see that we want to be able to pipe props and pass them to the final render callback function.</p><p>First of all, we need to make sure that only valid elements are composed together, further more we also need to make sure that the final function is actually a function. Let’s handle the simplest case: we only have a single function.</p><pre>function Pipe(elements, collectedProps = {}) {<br>  if (typeof elements === &quot;function&quot;) {<br>    return elements(collectedProps);<br>  }<br>  // handle multiple elements<br>}</pre><pre>// verify<br>render(<br>  &lt;Pipe title=&quot;Verify that Pipe1 works&quot;&gt;<br>    {({ title }) =&gt; &lt;h3&gt;{title}&lt;/h3&gt;}<br>  &lt;/Pipe&gt;<br>);</pre><p>Our next step is to handle multiple elements. By destructuring the elements collection, we can check if we have any elements left aside from the first, and if not, check if the only element is a function. If so, we can call the function with the collected props and return the result.</p><pre>function Pipe(elements, collectedProps = {}) {<br>  if (typeof elements === &quot;function&quot;) {<br>    return elements(collectedProps);<br>  }</pre><pre>  const [element, ...rest] = elements;<br>  if (rest.length === 0 &amp;&amp; typeof element === &quot;function&quot;) {<br>    return element(collectedProps);<br>  }</pre><pre>  // handle multiple elements<br>}</pre><p>In case the element is not a function, we need to check if the element is a valid React element and either create or clone the element. We have already seen this concept in the introduction part.</p><pre>function Pipe(elements, collectedProps = {}) {<br>  if (typeof elements === &quot;function&quot;) {<br>    return elements(collectedProps);<br>  }</pre><pre>  const [element, ...rest] = elements;<br>  if (rest.length === 0 &amp;&amp; typeof element === &quot;function&quot;) {<br>    return element(collectedProps);<br>  }</pre><pre>  const createElement = React.isValidElement(element)<br>    ? React.cloneElement<br>    : React.createElement;</pre><pre>  // override the existing children function<br>}</pre><p>To enable to collect the next props we need to a way to override the current children function, to call our Pipe function until we reach the last function.</p><pre>function children({ children, ...props }) {<br>  const nextProps = Object.assign({}, collectedProps, props);<br>  return Pipe(rest, nextProps);<br>}</pre><p>What is left is to override the children function via our previously defined createElement function.</p><pre>function Pipe({ children: elements, ...collectedProps }) {<br>  if (typeof elements === &quot;function&quot;) {<br>    return elements(collectedProps);<br>  }</pre><pre>  const [element, ...rest] = elements;<br>  if (rest.length === 0 &amp;&amp; typeof element === &quot;function&quot;) {<br>    return element(collectedProps);<br>  }</pre><pre>  const createElement = React.isValidElement(element)<br>    ? React.cloneElement<br>    : React.createElement;</pre><pre>  function children({ children, ...props }) {<br>    const nextProps = Object.assign({}, collectedProps, props);<br>    return Pipe({ children: rest, ...nextProps });<br>  }</pre><pre>  return createElement(element, {}, children);<br>}</pre><p>We have a working Pipe function, what is left is to validate if our function actually works.</p><pre>render(<br>  &lt;Pipe info=&quot;Pipe Function Rendering X and Y&quot;&gt;<br>    &lt;AddX initX={10} /&gt;<br>    &lt;AddY initY={20} /&gt;<br>    {({ x, y, info }) =&gt; (<br>      &lt;div&gt;<br>        &lt;h4&gt;Info: {info}&lt;/h4&gt;<br>        X: {x}<br>        &lt;br /&gt;<br>        Y: {y}<br>      &lt;/div&gt;<br>    )}<br>  &lt;/Pipe&gt;<br>);</pre><p>As seen we are able to collect all needed props and pass it the callback function, that does the actual rendering.</p><p>We should have a solid understanding how to transform elements in React now.</p><p>React’s top level API offers very useful utilities to help us with this. For more details consult the <a href="https://reactjs.org/docs/react-api.html">official React documentation</a>s.</p><p>Checkout this post as <a href="https://gist.github.com/busypeoples/3acfa392c8ce314d907c5772886ed3a8#file-1_transformingelementsinreact-md"><strong><em>Markdown</em></strong></a> or as <a href="https://gist.github.com/busypeoples/3acfa392c8ce314d907c5772886ed3a8#file-2_transformingelementsinreact-js"><strong><em>JavaScript</em></strong></a> file.</p><p>If you have any questions or feedback please connect via Twitter: <a href="https://twitter.com/sharifsbeat">A. Sharif</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e411c0f1bba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javascript-inside/transforming-elements-in-react-8e411c0f1bba">Transforming Elements In React</a> was originally published in <a href="https://medium.com/javascript-inside">JavaScript Inside</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Understanding Forms in React]]></title>
            <link>https://medium.com/javascript-inside/better-understanding-forms-in-react-a85d889773ce?source=rss-52e7bcc5db67------2</link>
            <guid isPermaLink="false">https://medium.com/p/a85d889773ce</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[A. Sharif]]></dc:creator>
            <pubDate>Sat, 23 Jun 2018 13:05:44 GMT</pubDate>
            <atom:updated>2018-06-23T13:05:44.892Z</atom:updated>
            <content:encoded><![CDATA[<p>The goal for this post is to get a better understanding of how to build forms in <strong>React</strong>. But before we see some actual implementations let’s try to better understand why this topic might seem complex in a React context.</p><h3>A. Sharif on Twitter</h3><p>Often heard that forms are a problem in React. What&#39;s the difference to writing them in HTML? onChange is consistent, state keeping is explained via the docs example. The problem people have is the validation part and that&#39;s not a React problem. https://t.co/8Z6Uu0M4YS</p><p>When talking about forms, we mostly have three areas in mind. <strong><em>Form Field Elements </em></strong>(representation), <strong><em>Form Values</em></strong> (state management) and <strong><em>Field Validations</em></strong> (validation). Let’s see what we can take-away by treating <strong>representation</strong>,<strong> state management</strong> and <strong>validation</strong> as independent areas.</p><h4><strong>Form State Management</strong></h4><p>Developers new to React seem to be surprised at how much manual work has to be done as compared to say <strong>jQuery</strong> to retrieve form values. In jQuery <a href="https://api.jquery.com/serializeArray/"><em>serializeArray</em></a> returns all form values as an array of objects for example. <em>(Thanks </em><a href="https://medium.com/u/b031a508ddaf"><em>Artem Sapegin</em></a><em> for the good comparison, also see </em><a href="https://twitter.com/iamsapegin/status/1010406113555120131"><em>https://twitter.com/iamsapegin/status/1010406113555120131</em></a><em>)</em></p><p>In React there are two ways to manage this state, via <em>controlled</em> and <em>uncontrolled</em> components. Let’s take a closer look at the former approach and <a href="https://reactjs.org/docs/forms.html">consult the documentation</a>.</p><blockquote>In HTML, form elements such as &lt;input&gt;, &lt;textarea&gt;, and &lt;select&gt; typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().</blockquote><blockquote>We can combine the two by making the React state be the “single source of truth”.</blockquote><blockquote><a href="https://reactjs.org/docs/forms.html#controlled-components">https://reactjs.org/docs/forms.html#controlled-components</a></blockquote><p>So any input element value that is controlled by React is described as a controlled component.</p><p>What does the actual implementation look like?</p><pre>onChange = event =&gt; {<br>  // taken straight from the official React Docs<br>  // <a href="https://reactjs.org/docs/forms.html#handling-multiple-inputs">https://reactjs.org/docs/forms.html#handling-multiple-inputs</a></pre><pre>  const target = event.target;<br>  const value = target.type === &quot;checkbox&quot; <br>    ? target.checked <br>    : target.value;<br>  const name = target.name;</pre><pre>  this.setState({<br>    [name]: value<br>  });<br>};</pre><p>As seen in the above example, we can retrieve <em>name</em> and <em>value</em> from event.target and update the value for given name.</p><p>Now we also need to call onChange when the input value has changed, which can be achieved via the onChange prop on an form input element.</p><pre>&lt;input<br>  name=&quot;active&quot;<br>  type=&quot;checkbox&quot;<br>  checked={form.active}<br>  onChange={onChange}<br>/&gt;</pre><p>We should have a basic understanding of how we can manage form state in React. Check the following example that shows how React controls the complete form state.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpymjxk5jnj&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fpymjxk5jnj&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fpymjxk5jnj%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/7399b52f2c183d16832345abf05e23b5/href">https://medium.com/media/7399b52f2c183d16832345abf05e23b5/href</a></iframe><h4>Form Validation</h4><p>Another important aspect when building forms is validation. We need a way to ensure that the<em> data is valid</em> and <em>display meaningful error messages</em> in case any input values are incorrect.</p><p>Typically we want to ensure that a required input is not empty, that a name has a certain string length, that an e-mail has the correct format or that two dependent fields have the same values.</p><p>Let’s take a look at the following <em>validation</em> function.</p><pre>const validate = ({ firstName, lastName }) =&gt; {<br>  return {<br>    firstName: !firstName || firstName.trim().length === 0<br>      ? &quot;First Name is required&quot;<br>      : false,<br>    lastName:<br>      !lastName || lastName.trim().length === 0<br>        ? &quot;Last Name is required&quot;<br>        : false<br>   };<br>};</pre><p>We need a way to <strong>represent any errors for given data</strong>. The actual validation implementation can vary, but in this example we want to represent any errors via an object. Every form field value can either be false or contain an error message. Interestingly our validation function doesn’t know anything about the form. It’s a standalone function that accepts any data and returns an object.</p><pre><em>In reality we could compose validation functions and run them against any data, we don’t have to be explicit about the specific names etc.</em></pre><p>What we need to do now, is enable to run the form data against the validation and display error messages when needed. Due to the fact that React renders the component as soon as the state has changed, we can run the validation every time we render. That also means there is no need to keep any errors in state.</p><p><strong>Every time we render, we validate the current form state against the validation.</strong></p><pre>render{) {<br> const {form, onChange } = this.state;<br> const errors = validate(form);<br>  return (<br>    &lt;form&gt;<br>      &lt;label&gt;<br>        active:<br>        &lt;input<br>          name=&quot;active&quot;<br>          type=&quot;checkbox&quot;<br>          checked={form.active}<br>          onChange={onChange}<br>        /&gt;<br>      &lt;/label&gt;<br>      {errors.firstName &amp;&amp; <br>         &lt;span className=&quot;error&quot;&gt;{errors.firstName}&lt;/span&gt;<br>       }<br>    &lt;/form&gt;<br>  );<br>}</pre><p>By separating the validation from the state management aspect, we can interchange how we want to validate our data, without being coupled to how state is managed. We can use a traditional validation library or write our own implementation.</p><p>Check the following example to see in more detail how this could be implemented.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F4q6j24zk2x&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F4q6j24zk2x&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F4q6j24zk2x%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eca63596bc8f97bf239b101532bc2d7/href">https://medium.com/media/5eca63596bc8f97bf239b101532bc2d7/href</a></iframe><h4>Form Representation</h4><p>Having covered the state management and the validation aspects, we also need to take care of the actual representation for our forms. React enables us to define components, compose these components etc. The only important fact to highlight here, is that <strong>our components should not know anything about how are form state is managed nor how this state is validated</strong>. As long as we separate the representation from these two aspects, we can build components that receive props and display information according to these props.</p><pre>const CheckBox = ({ label, error, onChange, name, value }) =&gt; ( <br>  &lt;label<br>    {label}:<br>    &lt;input <br>      name={name} <br>      type=&quot;checkbox&quot;<br>      checked={value} <br>      onChange={onChange} <br>    /&gt;<br>    {error &amp;&amp; &lt;span style={errorStyle}&gt;{error}&lt;/span&gt;}<br>  &lt;/label&gt;<br>);</pre><p>We can also build components that take care of handling <em>accessibility</em>, ensuring certain standards are considered etc. The important aspect here is that our representation is independent of the <strong><em>Form</em></strong> component and we can interchange these components without having to change the actual Form component.</p><h4>More advanced Concepts</h4><p>In the previous section we built a basic implementation of a form library. But in reality this implementation will only get us this far. Real world requirements might include the need to <strong>validate fields dynamically</strong> or on submit. <strong>Validate all fields or only fields that have been changed</strong> or<strong> instant validation only after an initial submit</strong>. Sometimes we might need to <strong>validate asynchronously</strong>, for example check if a given user name already exists etc.</p><p>Let’s try to see how we can solve these requirements while providing flexibility in user land.</p><p><em>How can we build a reusable Form component, without having to provide an extensive API for handling common scenarios?</em></p><p><strong>Asynchronous Validations</strong></p><p><strong><em>What if we delegate any async validations to a parent component?</em></strong> By taking this approach we can define the async validation outside our Form component and only pass down the validation function and the validation result to our Form component.</p><p>Take a look at the following example. Our Form component passes any props through to our render functionality. This means we re-render every time an asynchronous validation result is available.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fk9rkx2n9wr&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fk9rkx2n9wr&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fk9rkx2n9wr%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6192a883e95a2042e4c2824d7281392/href">https://medium.com/media/a6192a883e95a2042e4c2824d7281392/href</a></iframe><p><strong>Dynamic Validation</strong></p><p>Sometimes we need to validate fields dynamically, as soon as the value has changed, but leave any untouched inputs unvalidated. To be able to display error messages on changed fields, we need to keep track of which fields have actually changed.</p><p>This can be achieved by extending our form state to also know about which fields have been changed. For example we could extend the state object with a changedFields property. The same approach can be taken to check if a form has submitted or not. Again, we can the state object with a submitted property, which we can use when rendering the actual form.</p><p>Checkout the following example that displays this approach in more detail.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fk9rkx2n9wr&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fk9rkx2n9wr&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fk9rkx2n9wr%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6192a883e95a2042e4c2824d7281392/href">https://medium.com/media/a6192a883e95a2042e4c2824d7281392/href</a></iframe><p>Finally, we can provide user land more flexibility if we enable users to define not only what to <strong><em>render</em></strong> and the <strong><em>initialState</em></strong>, but also <strong>how to update</strong> the data.</p><pre>&lt;Form<br>  intitialState={{<br>    values: {<br>      active: false,<br>      firstName: &quot;&quot;,<br>      lastName: &quot;&quot;<br>    },<br>    submitted: false,<br>    changedFields: {}<br>  }}<br>  update={(state, name, value) =&gt; {<br>    return {<br>      ...state,<br>      values: { ...state.values, [name]: value },<br>      changedFields: { ...state.changedFields, [name]: true }<br>    };<br>  }}</pre><pre>...<br>/&gt;</pre><p><strong>Now our form doesn’t even have to know about our state or how to actually update it, it only takes care of managing the state.</strong></p><p>This approach is best understood, when applied via an example.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fyj6qrly17v&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fyj6qrly17v&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fyj6qrly17v%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/5432bee26c1cbf3dc1931d9747a23bfe/href">https://medium.com/media/5432bee26c1cbf3dc1931d9747a23bfe/href</a></iframe><h4>Summary</h4><p>Hopefully this write-up showed how even more complicated requirements can be tackled in React. As long as the validation, state management and representation aspects are independent from each other, we can extend and provide flexibility for the forms we are building. A good example for this approach is <a href="https://github.com/jaredpalmer/formik"><strong><em>Formik</em></strong></a> for example.</p><p>If there are better ways to solve these problems or if you have any questions, please leave a comment here or on <a href="https://twitter.com/sharifsbeat"><strong>Twitter</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a85d889773ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javascript-inside/better-understanding-forms-in-react-a85d889773ce">Better Understanding Forms in React</a> was originally published in <a href="https://medium.com/javascript-inside">JavaScript Inside</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Render Props, Render Callbacks And Higher-Order Components Are All Interchangeable]]></title>
            <link>https://medium.com/javascript-inside/render-props-render-callbacks-and-higher-order-components-are-all-interchangeable-1f01f56437fa?source=rss-52e7bcc5db67------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f01f56437fa</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[A. Sharif]]></dc:creator>
            <pubDate>Tue, 12 Jun 2018 11:34:57 GMT</pubDate>
            <atom:updated>2018-06-12T12:57:38.140Z</atom:updated>
            <content:encoded><![CDATA[<h4>Making rendering patterns interchangeable</h4><h4><strong>Introduction</strong></h4><p>There has been a lot of discussion around concepts like <strong>render-props</strong>, <strong>render-callbacks</strong> and <strong>higher-order components</strong> in the React community. Most commonly <strong><em>mixins</em></strong> where used to enhance a React Component with additional functionality like managing state f.e. After React moved from <strong><em>createClass</em></strong> to <strong><em>ES6</em></strong> classes, higher-order components became the favoured why to enhance components, but also the render callback pattern was in use, f.e. <a href="https://github.com/chenglou/react-motion"><em>react-motion</em></a> leverages children props to pass additional props and functionalities. A less common pattern was to use a so called render prop, so instead of the above mentioned approaches, you define a prop which accepts a callback. <a href="https://medium.com/u/7f9567e0d71c">Michael Jackson</a>’s <a href="https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce">“Use a Render Prop!”</a> made this pattern very popular.</p><h4>Basics</h4><p>All three mentioned patterns solve the same thing that <em>mixins</em> used to solve. Before we continue, let’s look at a couple of practical examples.</p><pre>If you understand the two concepts, skip this part and check the actual transformation examples.</pre><p><strong>Render Prop</strong></p><p>First, let’s build a small component that keeps track of our count state and renders any callback we pass to our <strong><em>render</em></strong> prop.</p><pre><em>Note: the callback prop can also have a different name than render, the pattern is only called render prop.</em></pre><p>Take a look at the following example:</p><pre>class CounterComponent extends React.Component {<br>  constructor(props) {<br>   super(props);<br>   this.state = { count: 0 };<br>  }<br>  update = type =&gt; {<br>    if (type === &quot;Inc&quot;) {<br>      this.setState(({ count }) =&gt; ({ count: count + 1 }));<br>    } else if (type === &quot;Dec&quot;) {<br>      this.setState(({ count }) =&gt; ({ count: count - 1 }));<br>    }<br>  };<br>  render() {<br>    return this.props.render({<br>      ...this.state,<br>      ...this.props,<br>      update: this.update<br>    });<br>  }<br>}</pre><p>In our <strong><em>CounterComponent</em></strong> render function we merge <em>props</em>, <em>state</em> and add an <em>update</em> function and pass it to the <em>render</em> prop.</p><p>Next, we will need a component that renders anything valuable to the screen.</p><pre>const Counter = ({ count, update }) =&gt; (<br>  &lt;div&gt;<br>    &lt;button onClick={() =&gt; update(&quot;Inc&quot;)}&gt;Inc&lt;/button&gt;<br>      {count}<br>    &lt;button onClick={() =&gt; update(&quot;Dec&quot;)}&gt;Dec&lt;/button&gt;<br>  &lt;/div&gt;<br>);</pre><p>Our <strong><em>Counter</em></strong> component accepts a count and an update function and displays an increment and decrement button as well as the current count.</p><p>Finally we can use our CounterComponent to enhance the Counter with the additional functionality.</p><pre>render(<br>  &lt;CounterComponent render={props =&gt; &lt;Counter {...props} /&gt;} /&gt;,<br>  document.getElementById(&quot;root&quot;)<br>);</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fvmr357j2z3&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fvmr357j2z3&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fvmr357j2z3%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/a64e80c1b599e553212ccbf0d5a45b6d/href">https://medium.com/media/a64e80c1b599e553212ccbf0d5a45b6d/href</a></iframe><h4>Higher-Order Components</h4><p>Now that we covered <em>render props</em>, let’s take a look at how we would construct a higher-order component that offers the exact same functionality.</p><pre>const withCounter = Component =&gt;<br>  class Hoc extends React.Component {<br>    constructor(props) {<br>    super(props);<br>    this.state = { count: 0 };<br>  }<br>  update = type =&gt; {<br>    if (type === &quot;Inc&quot;) {<br>      this.setState(({ count }) =&gt; ({ count: count + 1 }));<br>    } else if (type === &quot;Dec&quot;) {<br>      this.setState(({ count }) =&gt; ({ count: count - 1 }));<br>    }<br>  };<br>  render() {<br>    return &lt;Component <br>      {...this.state} <br>      {...this.props} <br>      update={this.update} <br>    /&gt;;<br>  }<br>};</pre><p>Looking at the above the example, we can see that we need to pass in our to be rendered Component to receive a brand new Component with the enhanced functionalities and props.</p><pre>const CounterExample = withCounter(Counter);</pre><pre>render(&lt;CounterExample /&gt;, document.getElementById(&quot;root&quot;));</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F73v481n5w0&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F73v481n5w0&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F73v481n5w0%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ea645251a4605b375c77da569fd9f91/href">https://medium.com/media/2ea645251a4605b375c77da569fd9f91/href</a></iframe><p>We should have covered the basic concepts now. Knowing that we can use different patterns to achieve the same results, we will focus on making theses concepts interchangeable.</p><h4>Transforming between render props and higher-order components</h4><p>Sometimes you might have a library that offers a <em>higher-order-component</em> but your favoured way of composing components is via <strong><em>JSX</em></strong>. Sometimes you might have a library that offers a render-prop, but you would like to compose multiple enhancing components via a <strong><em>compose</em></strong> function f.e. The interesting thing is that these concepts are interchangeable.</p><p>Let’s build on our previous examples and add transformation functions that would take a higher-order component and return a render-prop and vice versa.</p><pre><strong>fromHoc</strong>: HOC -&gt; RenderProp</pre><pre><strong>toHoc</strong>: RenderProp -&gt; HOC</pre><p>The <strong><em>toHoc </em></strong>functionality can be summed as:</p><pre><strong>toHoc</strong>: Render =&gt; Comp =&gt; props =&gt; ( <br>  &lt;Render {...props} render={props =&gt; &lt;Comp {...props} /&gt;} /&gt;<br>)</pre><p>Also check <a href="https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce"><strong><em>”Use a Render Prop!”</em></strong></a><strong><em> </em></strong>for an alternative implementation.</p><p>This converts a render prop to a higher order component.</p><pre>const withCounter = toHoc(CounterComponent);</pre><pre>const CounterExample = withCounter(Counter);</pre><p>Let’s verify this behaviour.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F43w3w184zx&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F43w3w184zx&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F43w3w184zx%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/25853947ef3d92e7103f203e5b983dd0/href">https://medium.com/media/25853947ef3d92e7103f203e5b983dd0/href</a></iframe><p>Converting from a higher-order component to a render-prop is slightly more complicated. We need to pass in a component with a render prop to the actual higher-order-component. All credits to <a href="https://medium.com/u/f8cf3d856c67">Brent Jackson</a>, <em>(</em><a href="https://github.com/jxnblk/refunk/blob/7a12bbda79b2423fef8d37439f9029f1aa19131b/src/component.js"><em>see this implemented in refunk</em></a><em>)</em>.</p><pre><strong>fromHoc</strong>: hoc =&gt; {<br>  class Render extends React.Component {<br>    render() { <br>      return this.props.children(this.props);<br>    }<br>  }<br>  return hoc(Render);<br>}</pre><p>Alternatively, this can also be accomplished without using a class baed approach. All credits to <a href="https://medium.com/u/beca78db39bf">Rodrigo Pombo</a> <em>(also </em><a href="https://twitter.com/pomber/status/992073195300835328"><em>check this example</em></a><em>)</em>.</p><pre><strong>fromHoc</strong>: hoc =&gt; hoc(props =&gt; props.render(props));</pre><p>Again, we can verify that this works as expected.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fcodesandbox.io%2Fs%2F2x7wv7q6jp&amp;src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F2x7wv7q6jp&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfb27cbbb61a6c772ae1361217a1bfed/href">https://medium.com/media/bfb27cbbb61a6c772ae1361217a1bfed/href</a></iframe><p>We can build a small helper that converts back and forth between higher-order-components and render-props. Check the following example. It should also be noted that we can initiate the toHoc with an additional render name, as the rendering prop might have a different name or be a child prop.</p><pre>const iso = {<br>  fromHoc: hoc =&gt; hoc(props =&gt; props.render(props)),<br>  toHoc: Render =&gt; Comp =&gt; props =&gt; ( <br>    &lt;Render {...props} render={props =&gt; &lt;Comp {...props} /&gt;} /&gt;<br>  )<br>};</pre><p>Finally, let’s see the different concepts back to back.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F382o0kq7k5&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F382o0kq7k5&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F382o0kq7k5%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cf82bc852fc35996057f3fbed981319/href">https://medium.com/media/2cf82bc852fc35996057f3fbed981319/href</a></iframe><h4>Summary</h4><p>Render props, render callbacks and higher-order component are interchangeable. For most cases render props will suffice, but you can transform back between these patterns in user land if needed.</p><p>Very special thanks to <a href="https://medium.com/u/f8cf3d856c67">Brent Jackson</a> <a href="https://medium.com/u/db72389e89d8">Kent C. Dodds</a> and <a href="https://medium.com/u/beca78db39bf">Rodrigo Pombo</a> for sorting out problems with the <strong><em>fromHoc</em></strong> implementation.</p><h4>Links</h4><p><a href="https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce"><strong><em>Use a Render Prop!</em></strong></a>: render prop pattern explained by <a href="https://medium.com/u/7f9567e0d71c">Michael Jackson</a></p><p><a href="https://reactpatterns.com/"><strong><em>React Patterns</em></strong></a>: excellent collection of React patterns by <a href="https://medium.com/u/49e1066348ce">michael chan</a></p><p><a href="https://reactjs.org/docs/higher-order-components.html"><strong><em>Higher-Order Components</em></strong></a>: Official React Docs</p><p><a href="https://reactjs.org/docs/render-props.html"><strong><em>Render Props</em></strong></a>: Official React Docs</p><p><a href="https://github.com/paypal/downshift"><strong><em>Downshift</em></strong></a>: Example of using a render prop via Downshift by <a href="https://medium.com/u/db72389e89d8">Kent C. Dodds</a></p><p><a href="https://github.com/jxnblk/refunk/blob/7a12bbda79b2423fef8d37439f9029f1aa19131b/src/component.js"><strong><em>Refunk</em></strong></a>: Example of converting a higher-order component to render prop by <a href="https://medium.com/u/f8cf3d856c67">Brent Jackson</a></p><p>If there are better ways to solve these problems or if you have any questions, please leave a comment here or on <a href="https://twitter.com/sharifsbeat"><strong>Twitter</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f01f56437fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javascript-inside/render-props-render-callbacks-and-higher-order-components-are-all-interchangeable-1f01f56437fa">Render Props, Render Callbacks And Higher-Order Components Are All Interchangeable</a> was originally published in <a href="https://medium.com/javascript-inside">JavaScript Inside</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hidden Knowledge In Software Teams]]></title>
            <link>https://medium.com/@sharifsbeat/hidden-knowledge-in-software-teams-9a6ea2f89c65?source=rss-52e7bcc5db67------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a6ea2f89c65</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[scrum]]></category>
            <dc:creator><![CDATA[A. Sharif]]></dc:creator>
            <pubDate>Wed, 23 May 2018 09:31:55 GMT</pubDate>
            <atom:updated>2018-05-23T12:15:56.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rkMTxWQ7vgK2HEZXMMVElg.png" /></figure><h4>On-boarding Everyone</h4><h4>Introduction</h4><h3>Twitter</h3><p>Been thinking about this for some time now. Are you the person that built a running system or are you the person that just started working on an existing system? There is a huge difference between the two. The creator has an understanding of the history of said system.</p><p>If you’ve been working in Software long enough you probably have seen the following two situations:</p><p><strong><em>a. Started working on a new system</em></strong></p><p><strong><em>b. Joined an already running system</em></strong></p><p>Systems evolve and change over time. Another trait they commonly have, is that they become complex, not necessarily on a code level, but in terms of interactions between parts of the system. <em>How does A behave in relation to B? </em>etc. To be fluent within a large system, you need an <strong>understanding of how everything is interconnected</strong>.</p><p>Very often a single contributor or a small number of people have an understanding of how the system works in its entirety. And as long as a single person is working on that system, this person can be productive, very productive even, moving with full speed. But at some point, more people will be needed to maintain and grow that system, as it can’t be handled efficiently by a single person anymore. <strong><em>It needs to scale from a contributor perspective.</em></strong></p><p>What happens naturally, is that development speed has to be exchanged with on-boarding time. It’s a trade-off, balancing short-term speed with long-term maintainability.</p><p>It means that <strong>the most productive member</strong>, has to <strong>invest time on-boarding</strong> the ones joining. This on-boarding process comes in different shapes and forms, but commonly achieved with the help of documentation and tests and other ways to describe an expected behaviour.</p><h4>Common Approaches</h4><p>In written form, we document architecture, sub-systems, the relation to each other. We might have an explicit documentation for setting up the project, in form of a readme file f.e. etc.<br>Further more, information can be manifested in <em>automation scripts</em>, in <em>project management tools</em> etc. As we can see, there is a lot of work needed when trying to make any knowledge, relevant to a system, explicit.</p><p>In reality these artifacts are often either <em>mostly outdated</em>, <em>available in parts</em> or <em>completely missing</em>. One or two people starting to build a system, don’t necessarily need this information because there is a common understanding of the details, as they have written it themselves.<br>They know why something behaves in a certain way, what happens when they change a certain part and what is needed to achieve a certain task. Due to the deep understanding of the systems internals they also might be able to move fast, confidently make changes and <strong>continuously ship features</strong>.</p><p><strong>Now what happens when the system requires more people, due to reaching a certain size or complexity?</strong></p><h4>Scaling the Team</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*tf-G7sbrRZkEXwRKIUYTvw.png" /></figure><p>Let’s think about a possible scenario where new people join the original authors. These creators need to on-board the new members.<br>The new group needs to understand design decisions, they need to figure out how everything is interconnected, they need to find out about boundaries and so and so forth. Due to the lack of historical context, they also need to figure out why certain implementations are built in a certain way, which might be obvious to the original contributors. There is hidden information that needs to be made explicit, step by step. From the perspective of the original author, it might seem that nothing is too complex, that reading the source code etc. should suffice. <strong>The more complex a system gets, the harder it is for an outsider to understand these things</strong>.</p><p>Things get tricky, when the original contributors think that everyone has the same understanding as they do. Mostly this is not the case. How does such thinking surface to the top? Some examples. <em>“That should take 5 minutes to implement”</em>, <em>“Obvious”</em>, <em>“That should be easy”</em> etc. <strong>Knowledge is contextual</strong>, it depends on an existing implementation, on understanding decisions made in the past etc.</p><p><strong>But what happens when a team skips this part of the transition?</strong></p><p><strong>What happens when the original authors assume that there is no need for further explanation, no need for a deeper documentation etc.?</strong></p><p><strong>What happens when the burden is shifted to the new team members?</strong></p><p>Hidden knowledge hinders <strong>team performance</strong>, people depend on one or two individuals to move forward. Most probably the rest of the team will try to understand certain parts by making small changes in isolation to prevent anything from breaking. They might try to go through available commits or comments to get a better understanding of what might happen when they change A. <em>Will changing A have an effect on B or C?</em> etc.</p><p>So, opposed to the original writers, new members will move cautiously, double checking any changes and trying to gather more information along the way. But what can we do to improve the transition phase?</p><p>As mentioned, further above, it’s an explicit<strong> trade-off between current and future productivity</strong>. Time needs to be shifted away from developing on full speed to knowledge transfer across the team. The further ahead knowledge is documented, the less stressful this phase is for anyone involved.</p><h4>Actions</h4><p>What are possible actions that can help in this situation? Just think about it from the perspective of someone joining an existing setup.</p><p><strong>Readme</strong></p><p>A readme that at least has information on how to setup a system f.e. <em>There is none or is it outdated?</em> This is a good opportunity to write or update that readme file. It might seem like nothing too special, at first glance. But how often have you checked if a readme file exists when having an initial look at a repository?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*EFN0FVpBKhXeLTTMroBmAw.png" /><figcaption>A readme file</figcaption></figure><p><strong>Documentation</strong></p><p>Documentation can manifest itself in a number of forms, the most conservative being something like a <strong>wiki</strong>, where high level decisions are described and where you can look up on <strong>architecture</strong> as well as other fundamental information. Also, documentation can be found in a <strong>design system</strong>, in a <strong>style-guide</strong>, via <strong>user stories</strong> etc. Depending on what we are building, a combination of multiple tools might be needed to sufficiently transport the required information. Sometimes these infos are partially available, which is a good opportunity to start updating or completing when new people join.</p><p><strong>Tests</strong></p><p>Tests is another way to describe expected behaviour. They can also provide confidence to new developers, due to signalling when something breaks, as opposed to finding out later on via a review or in production. Partly tests could even fall into the documentation category.</p><p><strong>Pair or Mob Programming</strong></p><p>Another strong approach to transferring knowledge is<strong> actually working together on an existing problem</strong>. It can highlight hidden knowledge, it can help quickly resolve questions and it provides confidence to new members when working on the actual feature, due to very short feedback cycles. This is also good opportunity to fill any gaps in regards to documentation, especially information that seems straightforward to the original contributors but not to anyone joining later on.</p><p><strong>Work together on Stories</strong></p><p>If pair or mob programming is not an option, then work together on a story, meaning break it up into small enough tasks. This is better than having every developer working on a single story.</p><p><strong>Understanding Context</strong></p><p>This one is probably the most important of all, and might hinder all other approaches: Is there a common understanding that there is hidden knowledge not available to every member working on that product/system? Everyone needs to watch out for phrases like <em>“easy” </em>and <em>“should take 5 minutes to implement”</em> etc.</p><p><strong>Being helpful and understanding</strong></p><p>This point is a logical conclusion of the previous one. Once there is an acceptance for the fact, that not everyone has the same level of knowledge regarding the system, there should be <strong>supportive environment</strong> for the newly joined. Supportive can mean, always ready to answer questions, provide help etc. Also means not to assume people are under-performing or <em>“don’t get it”</em>, just because it takes the original authors half the time to solve a problem. At the end it’s about <strong>moving from individual high-performers to a performing team</strong>.</p><p><strong>Ship less</strong></p><p>Deliberately choose to ship less when in a transformation phase. A team can’t keep on shipping at the same rate, while on-boarding parts of the team. <strong>Committing to less</strong>, gives room for the on-boarding phase. This is an important <strong>investment for future iterations</strong>.</p><p><strong>More</strong></p><p>There is more that can be done, but we probably have covered the more common ones, which we can build upon on. Other supportive approaches include scripts for importing-data, setting up local environments etc. All these help to further uncover hidden knowledge.</p><h4>Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYQACaSaQa2Ac9iAFl3XVg.png" /></figure><p>We know that if we want to go fast, it’s better to work in solo mode, but if we need long-term maintainability and extensibility it’s better to rely on a team. Sometimes it appears that teams can’t perform, relying on one or two high productive developers doing most of the work. Often the problem is hidden knowledge, meaning that not everyone has the same level of experience with or knowledge of a system.</p><p>What are your thoughts on this? Very interested in feedback, please leave a comment here or on <a href="https://twitter.com/sharifsbeat"><strong>Twitter</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a6ea2f89c65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fetching Data in ReasonML Pt. 1]]></title>
            <link>https://medium.com/@sharifsbeat/fetching-data-in-reasonml-pt-1-c06f3cc6b250?source=rss-52e7bcc5db67------2</link>
            <guid isPermaLink="false">https://medium.com/p/c06f3cc6b250</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reasonml]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[A. Sharif]]></dc:creator>
            <pubDate>Fri, 04 May 2018 14:55:55 GMT</pubDate>
            <atom:updated>2018-05-04T20:37:08.913Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding the basics</h4><h4>Introduction</h4><p>Most applications we build, need to interact with a server at some point. Fetching data from and sending data back to an endpoint is a common task we encounter when writing an app.<br>In this short tutorial we will learn how this can be accomplished in <a href="https://reasonml.github.io/"><strong>ReasonML</strong></a>.</p><p><em>What do we need to be enable to interact with an API endpoint?</em></p><p><a href="https://github.com/reasonml-community/bs-fetch"><strong><em>bs-fetch</em></strong></a> is a library, which forms a wrapper around the <em>fetch</em> API.</p><p><a href="https://github.com/glennsl/bs-json"><strong><em>bs-json</em></strong></a> is a compositional JSON encode/decode library for BuckleScript.</p><p>These two libraries will build the basis for interacting with an external API endpoint, everything else is available via <em>ReasonML</em> itself.</p><p>The outcome for this tutorial should be:</p><ol><li><strong>Understand fetching basics</strong></li><li><strong>Understand how to encode/decode data</strong></li></ol><h4><strong>Fetching Data Example</strong></h4><p>For the following tutorial we will use an API endpoint served via <a href="http://localhost:3000/"><strong><em>http://localhost:3000</em></strong></a><strong><em>/users</em></strong>. Our initial users structure is as follows:</p><pre>{<br>  &quot;users&quot;: [<br>    {<br>      &quot;id&quot;: 1,<br>      &quot;name&quot;: &quot;User A&quot;<br>    },<br>    {<br>      &quot;id&quot;: 2,<br>      &quot;name&quot;: &quot;User B&quot;<br>    },<br>    {<br>      &quot;id&quot;: 3,<br>      &quot;name&quot;: &quot;User C&quot;<br>    }<br>  ]<br>}</pre><p>What we can derive from this information, is that our <em>user</em> type can be defined as:</p><pre>type user = {<br>  id: int,<br>  name: string,<br>};</pre><p>Based on the above structure, we can also already define the possible states we want to display.</p><pre>type state =<br>  | NotAsked<br>  | Loading<br>  | Failure<br>  | Success(list(user));</pre><p>We have four possible states that we want represented inside our UI. If the loading has never been triggered, we would like to display a load button, else we are either currently loading the data or have been successful / encountered an error. This state shape prevents us from ever falsely displaying a loading icon while also displaying the user list f.e.</p><p>Now that we have our state shape defined, the next step is to figure out how to decode the data we want to retrieve. <em>bs-json</em> exposes Json.Encode/Json.Decode modules and we will use the Decode module to convert our expected users list back to Reason land.</p><pre>module Decode = {<br>  let user = user =&gt;<br>    Json.Decode.{<br>      id: field(&quot;id&quot;, int, user),<br>      name: field(&quot;name&quot;, string, user),<br>    };<br>};</pre><p>By defining the expected data structure and mapping via <em>field</em>, we can decode id and respectively map back to our user record. For example by defining:</p><p>field(&quot;id&quot;, int, user)</p><p>we ensure that <em>id</em> is an integer. What’s missing is the possibility to map over all the users and decode them one by one. Let’s extend our Decode module.</p><pre>module Decode = {<br>  // ...<br>  let users = json : list(user) =&gt; Json.Decode.list(user, json);<br>};</pre><p>This will enable us to use Decode.users later, when fetching the data. What’s still missing is the actual fetching operation, if you recall we already defined a url.</p><pre>let url = &quot;<a href="http://localhost:3000/users">http://localhost:3000/users</a>&quot;;</pre><p>To be able to make a request against the defined url, we will use <em>bs-fetch</em>, which is a thin wrapper around the Fetch API and wrap the operation inside a promise.</p><pre>let fetchUsers = () =&gt;<br>  Js.Promise.(<br>    Fetch.fetch(url)<br>    |&gt; then_(Fetch.Response.json)<br>    |&gt; then_(json =&gt;<br>         json |&gt; Decode.users |&gt; (users =&gt; Some(users) |&gt; resolve)<br>       )<br>    |&gt; catch(_err =&gt; resolve(None))<br>  );</pre><p>We also made our <em>fetchUsers</em> function lazy, meaning we will trigger the operation when needed. The approach is to try to run a fetch operation, decode the result and catch any possible errors. We will return an <strong><em>option</em></strong>, so we can react to the result accordingly. The <em>option</em> type is exposed by the standard library and is a <em>variant</em> with following definition:</p><pre>type <strong>option</strong>(‘a) = None | Some(‘a);</pre><p>Our next step is implement a component and tie everything together. Our <em>reducerComponent</em> will include the following actions:</p><pre>type action =<br>  | LoadUsers<br>  | LoadedUsers(list(user))<br>  | LoadUsersFailed;</pre><pre>let component = ReasonReact.reducerComponent(&quot;FetchComponent&quot;);</pre><p>Our initial state is that no fetch has been run, so we will default toNotAsked</p><pre>let make = _children =&gt; {<br>  ...component,<br>  initialState: () =&gt; NotAsked,<br>};</pre><p>The <em>reducer</em> function needs to handle all possible actions, that we previously defined.</p><pre>reducer: (action, _state) =&gt;<br>    switch (action) {<br>    | LoadUsers =&gt;<br>      ReasonReact.UpdateWithSideEffects(<br>        Loading,<br>        (<br>          self =&gt;<br>            Js.Promise.(<br>              fetchUsers()<br>              |&gt; then_(result =&gt;<br>                   switch (result) {<br>                   | Some(users) =&gt;<br>                      resolve(self.send(LoadedUsers(users)))<br>                   | None =&gt; resolve(self.send(LoadUsersFailed))<br>                   }<br>                 )<br>              |&gt; ignore<br>            )<br>        ),<br>      )<br>    | LoadedUsers(users) =&gt; ReasonReact.Update(Success(users))<br>    | LoadUsersFailed =&gt; ReasonReact.Update(Failure)<br>    },</pre><p>While <em>LoadedUsers</em> and <em>LoadUsersFailed, </em>depending on the outcome of the fetch operation, either update the state with Success or <em>Failure</em>, <em>LoadUsers</em> will need more explaining.</p><pre>| LoadUsers =&gt;<br>      ReasonReact.UpdateWithSideEffects(<br>        Loading,<br>        (<br>          self =&gt;<br>            /* ... */<br>        ),<br>      )</pre><p>With the <em>LoadUsers</em> action we need to do two things, first update the current state to Loading and second call our previously defined <em>fetchUsers</em> function start fetching the actually needed data. <strong><em>ReasonReact.UpdateWithSideEffects</em></strong> enables us to update the state and define a unsafe operation as a second argument.</p><pre>self =&gt;<br>  Js.Promise.(<br>    fetchUsers()<br>    |&gt; then_(result =&gt;<br>      switch (result) {<br>      | Some(users) =&gt; resolve(self.send(LoadedUsers(users)))<br>      | None =&gt; resolve(self.send(LoadUsersFailed))<br>      }<br>    )<br>    |&gt; ignore<br>  )</pre><p>If you recall, we defined our <em>fetchUsers</em> to return an option type. This enables us to pattern match over the result and either update the state with the newly defined users or declare the fetch as failed.</p><p>Finally inside render we handle all possible states.</p><pre>render: self =&gt;<br>    switch (self.state) {<br>    | NotAsked =&gt;<br>      &lt;div&gt;<br>        (str(&quot;Click to start load Users&quot;))<br>        &lt;button onClick=(_event =&gt; self.send(LoadUsers))&gt;<br>          (str(&quot;Load Users&quot;))<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    | Loading =&gt; &lt;div&gt; (str(&quot;Loading...&quot;)) &lt;/div&gt;<br>    | Failure =&gt; &lt;div&gt; (str(&quot;Something went wrong!&quot;)) &lt;/div&gt;<br>    | Success(users) =&gt;<br>      &lt;div&gt;<br>        &lt;h2&gt; (str(&quot;Users&quot;)) &lt;/h2&gt;<br>        &lt;ul&gt;<br>          (<br>            users<br>            |&gt; List.map(user =&gt;<br>                 &lt;li key=(string_of_int(user.id))&gt; <br>                   (str(user.name)) <br>                 &lt;/li&gt;<br>               )<br>            |&gt; Array.of_list<br>            |&gt; ReasonReact.array<br>          )<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>    },</pre><p>In this specific case, we don’t load automatically inside didMount, but rather initially display a load button. Once the load action has been triggered we then either display a loading text or the final result, which could be a list of uses or an error message.</p><p>Find the <a href="https://gist.github.com/busypeoples/46ac86e15769326743d01b754474e579"><strong>complete example here</strong></a>.</p><h4>Summary</h4><p>We should have a basic understanding of how to fetch data via ReasonML now. In part 2 we will try to understand how we to <em>create</em> or <em>update</em> and <em>delete</em><strong><em> </em></strong>data.</p><h4>Links</h4><p><a href="https://github.com/reasonml-community/bs-fetch"><strong>bs-fetch</strong></a></p><p><a href="https://github.com/glennsl/bs-json"><strong>bs-json</strong></a></p><p><a href="https://gist.github.com/busypeoples/46ac86e15769326743d01b754474e579"><strong>Basic Example</strong></a></p><p>If there are better ways to solve these problems or if you have any questions, please leave a comment here or on <a href="https://twitter.com/sharifsbeat"><strong>Twitter</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c06f3cc6b250" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Routing in ReasonReact]]></title>
            <link>https://medium.com/@sharifsbeat/routing-in-reasonreact-4517acaf2c8?source=rss-52e7bcc5db67------2</link>
            <guid isPermaLink="false">https://medium.com/p/4517acaf2c8</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reasonml]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[A. Sharif]]></dc:creator>
            <pubDate>Sun, 29 Apr 2018 19:50:03 GMT</pubDate>
            <atom:updated>2018-04-29T19:50:03.557Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction to Routing and Subscriptions</h4><h4>Introduction</h4><p>Once an application has more than one page, there will be a need to introduce some mechanism that correctly displays a selected page. In this short writeup we will take a look at how this is accomplished when working with a <a href="https://reasonml.github.io/reason-react/"><strong>ReasonReact</strong></a> app.</p><p>Routing in a Reason-React application is based on leveraging <strong>ReasonML</strong> language features like <em>pattern matching</em> as well as the fact that ReasonReact comes with a built-in <strong>Router</strong> which covers the most basic use cases.</p><p>The scope for this write-up can be summed up as:<br>1. Basic Routing<br>2. Advanced Routing<br>3. Implementing a Router Component</p><h4>ReasonReact.Router</h4><p>ReasonReact comes with a <a href="https://reasonml.github.io/reason-react/docs/en/router.html"><strong>built-in router</strong></a> since V0.3.1. The very minimal router leverages the existing library as well as language features and provides a basic solution for adding routing capabilities to an app.<br>Taking a look at the interface, we can see that it is truly a minimal implementation.</p><pre>module type Router = {<br>  type watcherID;<br>  type url = {<br>    path: list(string),<br>    hash: string,<br>    search: string,<br>  };<br>  let watchUrl: (url =&gt; unit) =&gt; watcherID;<br>  let unwatchUrl: watcherID =&gt; unit;<br>};</pre><p>The <em>url</em> record consists of <em>hash</em>, <em>path</em> and <em>search</em> and we can subscribe and unsubscribe to any url changes via <em>watchUrl</em> and <em>unwatchUrl</em>.</p><p><em>watcherID</em> is returned when subscribing to <em>watchUrl</em> and is required when needing to unsubscribe via <em>unwatchUrl</em>.</p><p>Let’s see how we can incorporate routing into a multi-page application. For simplicity reasons let’s assume we have two page components: <strong>Dashboard </strong>and<strong> Users</strong>.</p><p>Our top level <strong>App</strong> component needs to route to the selected page, which for now could be represented via <em>http://localhost:3000#users</em>. So we’re interested in accessing the current url <em>hash</em> and navigating to the corresponding component.</p><p>First off let’s define a <em>page</em> type representing any possible pages.</p><pre>type page =<br>  | Dashboard<br>  | Users;</pre><p>Let’s assume that we have an <strong>App</strong> module setup, as well as the page components. Out App component might look something like this:</p><pre>module App = {<br>  type state = {route: page};<br>  type action =<br>    | UpdatePage(page);<br>  let component = ReasonReact.reducerComponent(&quot;App&quot;);<br>  let make = _children =&gt; {<br>    ...component,<br>    initialState: () =&gt; {route: Dashboard},<br>    reducer: (action, _state) =&gt;<br>      switch (action) {<br>      | UpdatePage(route) =&gt; ReasonReact.Update({route: route})<br>      },<br>    render: ({state}) =&gt;<br>      &lt;div&gt;<br>        (<br>          switch (state.route) {<br>          | Dashboard =&gt; &lt;Dashboard /&gt;<br>          | Users =&gt; &lt;Users /&gt;<br>          }<br>        )<br>      &lt;/div&gt;,<br>  };<br>};</pre><p>You might have noticed that there is an <em>action</em> type defined already and that <em>Dashboard</em> is being defined as the default route inside <strong>initialState</strong>.<br>Where would we subscribe to any events? Probably inside <strong>didMount</strong> and then unsubscribing inside <strong>willUnmount</strong>. Interestingly ReactReason also introduced <a href="https://reasonml.github.io/reason-react/docs/en/subscriptions-helper.html"><strong>subscriptions</strong></a> via V0.3.1, which means we can pass in a subscribe, unsubscribe tuple, that gets called when the component mounts and respectively unmounts.</p><pre>subscriptions: self =&gt; [<br>  Sub(<br>    () =&gt;<br>      ReasonReact.Router.watchUrl(url =&gt;<br>        switch (url.hash) {<br>        | &quot;users&quot; =&gt; self.send(UpdatePage(Users))<br>        | _ =&gt; self.send(UpdatePage(Dashboard))<br>        }<br>      ),<br>    ReasonReact.Router.unwatchUrl,<br>  ),<br>],</pre><p>Taking a look at the above code, one can notice that we’re pattern matching over the url <em>hash</em> and updating the state with the selected router.</p><p>If we change the hash to <strong><em>#users</em></strong> Dashboard will still be rendered. This is because we need to access the initial url record. What’s been missing from the interface definition is <em>dangerouslyGetInitialUrl</em>.</p><pre>module type Router = {<br>  ...<br>  let dangerouslyGetInitialUrl: unit =&gt; url;<br>};</pre><p>If we rework the <em>initialState</em> and use <em>dangerouslyGetInitialUrl</em> the compiler will complain because <em>hash</em> is a string. What’s missing is a mapping function which accepts a <em>url</em> and returns the appropriate <em>page</em> and vice versa. Let’s implement a module that handles this.</p><pre>module type Mapper = {<br>  let toPage: ReasonReact.Router.url =&gt; page;<br>  let toUrl: page =&gt; string;<br>};</pre><p>The <strong>Mapper</strong> for the existing example could be implemented like the following.</p><pre>module Mapper: Mapper = {<br>  let toPage = (url: ReasonReact.Router.url) =&gt;<br>    switch (url.hash) {<br>    | &quot;users&quot; =&gt; Users<br>    | _ =&gt; Dashboard<br>    };<br>  let toUrl = page =&gt;<br>    switch (page) {<br>    | Users =&gt; &quot;users&quot;<br>    | _ =&gt; &quot;dashboard&quot;<br>    };<br>};</pre><p>Now that we have a <em>Mapper</em> module in place, we can update <em>initialState</em> to return the appropriate route.</p><pre>initialState: () =&gt; {<br>  route: ReasonReact.Router.dangerouslyGetInitialUrl() <br>    |&gt; Mapper.toPage,<br>},</pre><p>You might also have noticed that our <strong>toPage</strong> function also has similarities to the subscription function, enabling us to refactor our <em>subscriptions</em> significantly.</p><pre>subscriptions: self =&gt; [<br>  Sub(<br>    () =&gt;<br>      ReasonReact.Router.watchUrl(url =&gt;<br>        self.send(UpdatePage(Mapper.toPage(url)))<br>      ),<br>      ReasonReact.Router.unwatchUrl,<br>    ),<br>  ]</pre><p>We have a very basic routing mechanism in place. Check the <a href="https://gist.github.com/busypeoples/7d64122be3085081a754ec93fed81116">complete example here</a>.</p><h4>More advanced routing</h4><p>Let’s build on the previous example and see how one could handle a more realistic scenario, where we might want to display a specific user, depending on a specified id.</p><p>The first step is to extend the page type.</p><pre>type page =<br>  | Dashboard<br>  | Users<br>  | User(int);</pre><p>Next, we need to update the <em>Mapper</em> module.</p><pre>module Mapper: Mapper = {<br>  let toPage = (url: ReasonReact.Router.url) =&gt;<br>    switch (url.path) {<br>    | [&quot;users&quot;] =&gt; Users<br>    | [&quot;user&quot;, id] =&gt; User(int_of_string(id))<br>    | _ =&gt; Dashboard<br>    };<br>  let toUrl = page =&gt;<br>    switch (page) {<br>    | Users =&gt; &quot;users&quot;<br>    | User(id) =&gt; &quot;user/&quot; ++ string_of_int(id)<br>    | _ =&gt; &quot;dashboard&quot;<br>    };<br>};</pre><p>We have switched from <em>hash</em> to <em>path</em> when accessing the url. Finally we need to adapt the <em>render</em> function to cover the User(int) case.</p><pre>render: ({state}) =&gt;<br>  &lt;div&gt;<br>    (<br>      switch (state.route) {<br>      | Dashboard =&gt; &lt;Dashboard /&gt;<br>      | Users =&gt; &lt;Users /&gt;<br>      | User(id) =&gt; &lt;User id /&gt;<br>      }<br>    )<br>  &lt;/div&gt;</pre><p>With just a couple of changes, we were able to cover a more advanced scenario. There is not much more we need to know, to implement routing in a ReasonReact app. In the final section, we will build a Router component.</p><p>Check the <a href="https://gist.github.com/busypeoples/ebb4a34130701d042115523b28da2afc">complete example here</a></p><h4>Building A Router Component</h4><p>We might want to build a <strong>Router</strong> Component that takes care of the route handling. Let’s think about how the <em>Config</em> record could be designed.</p><pre>module type Config = {<br>  type route;<br>  let toUrl: route =&gt; string;<br>  let toRoute: ReasonReact.Router.url =&gt; route;<br>};</pre><p>Interestingly, we could reuse most parts of the previous App component code.</p><pre>module CreateRouter = (Config: Config) =&gt; {<br>  type route = Config.route;<br>  type renderProps = {<br>    updateRoute: route =&gt; unit,<br>    route,<br>  };<br>  type state = {route};<br>  type action =<br>    | UpdateRoute(route);<br>  let component = ReasonReact.reducerComponent(&quot;Router&quot;);<br>  let make = (~render, _children) =&gt; {<br>    ...component,<br>      initialState: () =&gt; {<br>      route: ReasonReact.Router.dangerouslyGetInitialUrl()<br>        |&gt; Config.toRoute,<br>    },<br>    subscriptions: self =&gt; [<br>      Sub(<br>        () =&gt;<br>          ReasonReact.Router.watchUrl(url =&gt;<br>            self.send(UpdateRoute(Config.toRoute(url)))<br>          ),<br>        ReasonReact.Router.unwatchUrl,<br>      ),<br>    ],<br>    reducer: (action, _state) =&gt;<br>      switch (action) {<br>      | UpdateRoute(route) =&gt; ReasonReact.Update({route: route})<br>      },<br>    render: self =&gt;<br>      render({<br>        updateRoute: route =&gt; self.send(UpdateRoute(route)),<br>        route: self.state.route,<br>      }),<br>  };<br>};</pre><p>There is a slight difference inside <em>render</em>, where we will use a <strong>render</strong> <strong>prop</strong> and pass the current <em>route</em> as well as the <em>updateRoute</em> to the provided render function.</p><p>If you go back to our previous example, this could be refactored to the following now:</p><pre>type page =<br>  | Dashboard<br>  | Users<br>  | User(int);</pre><pre>module Config = {<br>    type route = page;<br>    let toRoute = (url: ReasonReact.Router.url) =&gt;<br>      switch (url.path) {<br>      | [&quot;user&quot;, id] =&gt; User(int_of_string(id))      <br>      | [&quot;users&quot;] =&gt; Users<br>      | _ =&gt; Dashboard<br>      };<br>    let toUrl = route =&gt;<br>      switch (route) {<br>      | User(id) =&gt; &quot;/user/&quot; ++ string_of_int(id)<br>      | Users =&gt; &quot;/users&quot;<br>      | Dashboard =&gt; &quot;/&quot;<br>      };<br>  };</pre><pre>module Router = CreateRouter(Config);</pre><p>After defining the <em>Config</em>, we can now use the <em>Router</em> component inside the <em>App</em> component.</p><pre>module App = {<br>  let component = ReasonReact.statelessComponent(&quot;App&quot;);<br>  let make = _self =&gt; {<br>    ...component,<br>    render: _self =&gt;<br>      &lt;Router<br>        render=(<br>          ({route}) =&gt;<br>            switch (route) {<br>            | Dashboard =&gt; &lt;Dashboard /&gt;<br>            | User(id) =&gt; &lt;User id /&gt;<br>            | Users =&gt; &lt;Users /&gt;<br>            }<br>        )<br>      /&gt;,<br>  };<br>};</pre><p>Building on this approach, we could also implement a <strong>Link</strong> component for updating routes.</p><pre>module Link = {<br>  let component = ReasonReact.statelessComponent(&quot;Link&quot;);<br>  let make = (~route, ~toUrl, ~render, _children) =&gt; {<br>    ...component,<br>    render: _self =&gt; {<br>      let href = toUrl(route);<br>      let onClick = e =&gt; {<br>        ReactEventRe.Mouse.preventDefault(e);<br>        ReasonReact.Router.push(href);<br>      };<br>      &lt;a href onClick&gt; (render()) &lt;/a&gt;;<br>    },<br>  };<br>};</pre><p>Then use the <em>Link</em> component whenever we want to update the route.</p><pre>&lt;Link route=Users toUrl=Config.toUrl render=(() =&gt; str(&quot;Users!&quot;)) /&gt;</pre><p>Check the <a href="https://gist.github.com/busypeoples/1649ebe07c9e70d9c58fa60a9b43d08b">complete example here</a>.</p><h4>Outro</h4><p>Routing basically comes out of the box with ReasonReact.</p><h4>Links</h4><p><a href="https://reasonml.github.io/reason-react/docs/en/router.html"><strong>ReasonReact Router</strong></a></p><p><a href="https://reasonml.github.io/reason-react/docs/en/subscriptions-helper.html"><strong>ReasonReact Subscriptions</strong></a></p><p><a href="https://gist.github.com/busypeoples/7d64122be3085081a754ec93fed81116"><strong>Basic Example</strong></a></p><p><a href="https://gist.github.com/busypeoples/ebb4a34130701d042115523b28da2afc"><strong>Advanced Example</strong></a></p><p><a href="https://gist.github.com/busypeoples/1649ebe07c9e70d9c58fa60a9b43d08b"><strong>Router Component Example</strong></a></p><p>If there are better ways to solve these problems or if you have any questions, please leave a comment here or on <a href="https://twitter.com/sharifsbeat"><strong>Twitter</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4517acaf2c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>