<?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 Simon Boudrias on Medium]]></title>
        <description><![CDATA[Stories by Simon Boudrias on Medium]]></description>
        <link>https://medium.com/@SBoudrias?source=rss-57e9bedd5cc5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zOnQoL04GY7Q-9dzmgKvew.jpeg</url>
            <title>Stories by Simon Boudrias on Medium</title>
            <link>https://medium.com/@SBoudrias?source=rss-57e9bedd5cc5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:32:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SBoudrias/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[Writing maintainable forms with redux]]></title>
            <link>https://medium.com/@SBoudrias/writing-maintainable-forms-with-redux-2ef30b5d0e35?source=rss-57e9bedd5cc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ef30b5d0e35</guid>
            <category><![CDATA[reselect]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Simon Boudrias]]></dc:creator>
            <pubDate>Fri, 23 Dec 2016 21:40:56 GMT</pubDate>
            <atom:updated>2016-12-24T21:18:44.645Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Writing forms is often a major part of most UI engineers works. Whether it’s a series of input fields, or dynamic controls, a form is the basic concept behind any data manipulation.</p><p>A lot of libraries are out there proposing solutions to help organize forms. But what you want might just be a simple recipe to keep forms simple and organized.</p><p>So what are the base requirements for an usable form?</p><ol><li>Needs validation</li><li>Load pre-existing data (pre-fill or edit)</li><li>Keep track of changes</li></ol><h3>Form Reducer</h3><p>First step is creating a reducer to store our form. We basically want to be able to update the form with new values and reset it once we’re done.</p><pre>const UPDATE_PERSON_FORM = &#39;UPDATE_PERSON_FORM&#39;;<br>const RESET_PERSON_FORM = &#39;RESET_PERSON_FORM&#39;;</pre><pre>const updatePersonForm = (form) =&gt; ({<br>  type: UPDATE_PERSON_FORM,<br>  form<br>});</pre><pre>const resetPersonForm = () =&gt; {type: RESET_PERSON_FORM};</pre><pre>const PersonFormReducer = (state={}, action) =&gt; {<br>  switch (action.type) {<br>    case UPDATE_PERSON_FORM:<br>      return {<br>        ...state,<br>        ...action.form,<br>      };<br>    case RESET_PERSON_FORM:<br>      return {};<br>    default:<br>      return state;<br>  }<br>};</pre><p>The reducer should stay simple, the magic will happens in selectors.</p><h3>Selectors</h3><p>To me, selectors are a core concept of redux. You might be using <a href="https://github.com/reactjs/reselect">reselect</a>, but simple functions work as well.</p><p>The first selector we need is one that’ll select the form values. This entails handling default values, merging pre-existing data and potentially imposing bounds on values.</p><pre>const personFormSelector = createSelector([<br>  (state) =&gt; state.personForm,<br>  (state, id) =&gt; state.person.by_id[id],<br>], (form, person) =&gt; {<br>  return {<br>    ...person || {},<br>    ...form,<br>  };<br>});</pre><p>This selector is assuming the form and the models keys are named the same. If that’s not your case, the form selector is a good place to handle name mapping. It’s also a good place to enforce values boundaries/filtering.</p><pre>const personFormSelector = createSelector([<br>  (state) =&gt; state.personForm,<br>  (state, id) =&gt; state.person.by_id[id],<br>], (form, person) =&gt; {<br>  var formValues = {<br>    firstName: &#39;&#39;,<br>    ...person || {},<br>    ...form,<br>  };</pre><pre>  // Impose lower bound on age<br>  formValues.age = Math.max(13, parseInt(formValues.age));</pre><pre>  return formValues;<br>});</pre><p>This selector should contains all the logic necessary to prefill the form with default values and existing entity values, enforce validation and filtering. Separating final values computation from the redux reducer is useful to make your system more robust towards bad values you might have stored in your database in the past, or to be resilient to bad/wrong code updating the store itself.</p><p>Next step, we need a selector handling validation.</p><pre>const personFormErrorsSelector = createSelector([<br>  personFormSelector,<br>], (form) =&gt; {<br>  var errors = {};</pre><pre>  if (form.firstName.length &gt; 50) {<br>    errors.firstName = &#39;First name cannot contain more than 50 characters&#39;;<br>  }</pre><pre>  if (!isValidEmail(form.email)) {<br>    errors.email = &#39;Please enter a valid email&#39;;<br>  }</pre><pre>  return errors;<br>});</pre><p>Take the form as an argument, and check if values are valid. If they’re not, fill the <em>error</em> object with error messages.</p><h3>Binding to the view</h3><p>We’ll use react for the view layer, but this pattern is generic enough that it could work for many different frameworks.</p><pre>class PersonForm extends React.Component {<br>  onChange(e) {<br>    this.props.updatePersonForm({<br>      [e.target.name]: e.target.value,<br>    });<br>  }</pre><pre>  onSubmit() {<br>    // If there&#39;s no error, the object is empty<br>    if (Object.keys(this.props.errors).length &gt; 0) {<br>      alert(&#39;Please fix the errors before submitting&#39;);<br>      return;<br>    }</pre><pre>    this.props.onSubmit(this.props.form);<br>  }<br>  <br>  render() {<br>    var {form, errors} = this.props;<br>    return (<br>      &lt;form onSubmit={this.onSubmit}&gt;<br>        &lt;label&gt;<br>          First Name<br>          &lt;input name=&quot;firstName&quot; value={form.firstName} onChange={this.onChange}/&gt;<br>          {errors.firstName}<br>        &lt;/label&gt;<br>        &lt;label&gt;<br>          Last Name<br>          &lt;input name=&quot;email&quot; value={form.email} onChange={this.onChange}/&gt;<br>          {errors.email}<br>        &lt;/label&gt;<br>      &lt;/form&gt;<br>    );<br>  }<br>}</pre><pre>export default connect(<br>  (state, {id}) =&gt; ({<br>    form: personFormSelector(state, id),<br>    errors: personFormErrorsSelector(state),<br>  }),<br>  {updatePersonForm}<br>)(PersonForm);</pre><p>Using react-redux, we bind our view to our form object. Then we only need to use it:</p><pre>&lt;PersonForm id={editedPersonId} onSubmit={savePersonForm}/&gt;</pre><h3>Wrapping up</h3><p>So really that’s how there really is to it. This basic architecture is extremely flexible and extendable; but it keeps parts of logic well defined and separated.</p><p>Want to display a loader while you’re sending data through ajax? Return a promise from <em>onSubmit</em> and display a loader until success or failure.</p><p>Want to have different levels of form errors? Add a <em>personFormWarningSelector</em>.</p><p>My team’s been using this pattern for handling form with redux for about a year on production. So far it provided us enough flexibility to handle most edge cases our UI might require. It also keep the barrier of entry lower for new developers joining our team given there’s no extra library own API to learn to get up and running working with forms.</p><p>I hope you’ll find this recipe useful too. Let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ef30b5d0e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>