<?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 Stjepan Golemac on Medium]]></title>
        <description><![CDATA[Stories by Stjepan Golemac on Medium]]></description>
        <link>https://medium.com/@stjepan.golemac?source=rss-512a4050aac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AxOSgfNSNfsnncoMQhyHqQ.jpeg</url>
            <title>Stories by Stjepan Golemac on Medium</title>
            <link>https://medium.com/@stjepan.golemac?source=rss-512a4050aac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 27 Aug 2018 11:03:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/@stjepan.golemac" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Hi Marco,]]></title>
            <link>https://medium.com/@stjepan.golemac/hi-marco-7bb3f57d4641?source=rss-512a4050aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb3f57d4641</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux-saga]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Stjepan Golemac]]></dc:creator>
            <pubDate>Thu, 12 Jul 2018 20:35:48 GMT</pubDate>
            <atom:updated>2018-07-12T20:35:48.137Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Marco,</p><p>I am glad that you find this article useful! I suppose that you are asking me about the prevention of endless looping.</p><p>The code from the provided repo will surely loop to eternity if the REQUEST action fails every time. The solution here could be adding a retry counter to the action. Such information would allow the monitor saga to abandon the action after the configured number of attempts.</p><p>If you look at the Flux Standard Action (<a href="https://github.com/redux-utilities/flux-standard-action">https://github.com/redux-utilities/flux-standard-action</a>), it says the best place to put such data is in the meta property of the action.</p><p>You could extend the functionality of the monitor saga to increment the counter every time it encounters a failed action.</p><p>Example:</p><p>starting to monitor action:<br>{ type: ‘FOO_REQUEST’, payload: { … } }</p><p>action failed, refresh the token and dispatch it again:<br>{ type: ‘FOO_REQUEST’, payload: { … }, meta: { retry: 1 } }</p><p>…</p><p>action failed again, retry counter is &gt; 3, ignore the action…</p><p>I hope this is understandable. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb3f57d4641" width="1" height="1">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complex App Logic With Redux And Redux Saga: Write an Authentication Monitor]]></title>
            <link>https://blog.bitsrc.io/complex-app-logic-with-redux-and-redux-saga-write-an-authentication-monitor-2f5672303d7d?source=rss-512a4050aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f5672303d7d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Stjepan Golemac]]></dc:creator>
            <pubDate>Thu, 21 Jun 2018 15:30:39 GMT</pubDate>
            <atom:updated>2018-06-21T15:30:39.201Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using sagas to monitor and react when dealing with authentication failures.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JWk8pJviAxXHWiJuGP5zg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/pDKoVuXYKxU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">JOHN TOWNER</a> on <a href="https://unsplash.com/search/photos/task?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A common mistake when writing business logic in web apps is code duplication. If a component needs to fetch user data the first thing that comes to mind is fetching it in the componentDidMount hook. The problem with that is repeating the code in every component that needs the same data.</p><p>What if the logic for data fetching is written only once, and just invoked when needed?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*9sE2DFGvgMc3MHytdN_EDg.gif" /><figcaption>Tell me more.</figcaption></figure><h3>Redux saga</h3><p>Imagine separate threads that can listen to dispatched actions, and react to them by executing some logic and dispatching other actions. That is technically not accurate but good enough to get an initial idea.</p><p>For those that want to thoroughly understand redux-saga, be advised to see the <a href="https://redux-saga.js.org/">official documentation</a>.</p><p>It is a Redux middleware that executes sagas (for now think of them as plain functions) based on dispatched actions. There are some similarities to Redux reducers although they are very different things.</p><ul><li>there is a root saga (remember root reducer?)</li><li>they can read and change state (indirectly)</li><li>they can be combined and reused</li></ul><h4>Why saga?</h4><p>The name redux-saga comes from the concept of long-running transactions that are modeled and known by the <em>saga design pattern</em> name. The pattern attempts to resolve the problem of complex interactions between different services.</p><p>For example, when the user is requesting a particular resource from a server the request needs to be authenticated. The process of authentication can be modeled as a saga.</p><p>Web applications often have many processes that could benefit from this design pattern such as multi-stage data fetching, interpreting complex user interactions and monitoring the user or application state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*7sLqH7JR0sW__xjFMiUMTA.png" /><figcaption>Saga is the comb for the tangled hair of application logic</figcaption></figure><h4>Generators</h4><p>In redux-saga, sagas are implemented with the help of generator functions. They are a part of the ES6 standard and are supported by all major browsers besides IE. With the help from <a href="https://babeljs.io/">Babel</a>, generators can be used in IE and older browsers too.</p><p>A generator cannot be used directly as it needs to be instanced before. After the instantiation, it is executed by calling the next() function. When the generator is finished it will return the done flag.</p><pre>function* generator() {<br>  yield 1<br>  yield 2<br>  yield 3<br>}</pre><pre>const gen = generator()</pre><pre>gen.next()<br>// { value: 1 }</pre><pre>gen.next()<br>// { value: 2 }</pre><pre>gen.next()<br>// { value: 3, done: true }</pre><p>The generator code should be straightforward except the yield keyword. It is very similar to the return keyword as it returns the value. The difference is that when the next() function is called again, execution will continue from the last yield statement.</p><p>Here is a generator that outputs numbers from the Fibonacci sequence.</p><pre>function* fibGenerator(limit) {<br>  let current = 0<br>  let next = 1<br>  let temp</pre><pre>  for (let i = 0; i &lt; limit; i++) {<br>    temp = current<br>    current = next<br>    next = temp + next<br>    yield current<br>  }<br>}</pre><pre>const fib = fibGenerator(3)</pre><pre>fib.next()<br>// { value: 1 }</pre><pre>fib.next()<br>// { value: 1 }</pre><pre>fib.next()<br>// { value: 2, done: true }</pre><p>For an in-depth introduction to generators, I suggest starting with this <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">MDN web doc</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*_wkqF4M5YZ1ajxn_ETx-xA.gif" /><figcaption>Enough theory, now the main attraction</figcaption></figure><h3>Authentication Monitor</h3><p>Every web application needs to fetch its data from a server that may or may not be protected from public access. The most common way of authentication today is the usage of JSON web tokens or <a href="https://jwt.io/">JWT</a>.</p><p>A client needs to include the server-issued JWT in the header of every request that queries non-public data. When the JWT is expired or not valid the server will return the 401 status code.</p><p>Authentication failure can be handled in many different ways and often the best approach is to refresh the token and try again. That process can be isolated and solved with sagas.</p><p>For the example to be simple and understandable there should be some rules for the Redux logic.</p><h4>Assumptions</h4><ol><li>Every interaction with the server is implemented as a three action process consisting of these states: REQUEST, SUCCESS, FAILURE.</li><li>Failures should contain the error as a payload of the action.</li><li>There should be a mechanism to prevent monitoring of some actions.</li></ol><h4>Implementation</h4><p>For those who want to see the finished code, it is available in <a href="https://github.com/stjepangolemac/monitor-saga">this repo</a>.</p><p><a href="https://github.com/stjepangolemac/monitor-saga">stjepangolemac/monitor-saga</a></p><p>Here’s a step by step explanation of the code.</p><p>Actions that do not trigger new requests should not be monitored and they could be identified by the lack of the <em>REQUEST</em> suffix. Some actions should not be monitored for a range of different reasons so it is essential to recognize them too. The easiest way is to put them in a list.</p><pre>const ignoreActionTypes = [&#39;TOKEN_REFRESH&#39;]</pre><pre>function monitorableAction(action) {<br>  return action.type<br>    .includes(&#39;REQUEST&#39;) &amp;&amp; ignoreActionTypes<br>      .every(fragment =&gt; !action.type.includes(fragment))<br>}</pre><p>A couple of helper functions will prevent code duplication and make the code more readable and understandable. An action is identified by stripping the state suffix from the action type. For example, GET_PROFILE_REQUEST is actually a GET_PROFILE action with REQUEST state.</p><pre>function identifyAction(action) {<br>  return action.type.split(&#39;_&#39;).slice(0, -1).join(&#39;_&#39;)<br>}<br>function getSuccessType(action) {<br>  return `${identifyAction(action)}_SUCCESS`<br>}<br>function getFailType(action) {<br>  return `${identifyAction(action)}_FAILURE`<br>}</pre><p>For an easier understanding, let see how the monitor is fired before it’s implementation.</p><pre>export default function*() {<br>  yield takeEvery(monitorableAction, monitor)<br>}</pre><p>If an action needs to be monitored the monitor will be spawned, otherwise nothing will happen. After the action is classified as monitorable the saga waits for a SUCCESS or FAILURE action.</p><pre>function* monitor(monitoredAction) {<br>  console.log(&#39;started monitoring&#39;, monitoredAction.type)<br>  const { fail } = yield race({<br>    success: take(getSuccessType(monitoredAction)),<br>    fail: take(getFailType(monitoredAction)),<br>  })</pre><pre>  ...</pre><p>There is no need to do anything if the process succeeds so there is only a check for a failure which is a result of an invalid token.</p><pre>...</pre><pre>if (fail &amp;&amp; fail.payload &amp;&amp; fail.payload.code === 401) {<br>  console.log(&#39;detected 401, refreshing token&#39;)<br>  yield put(userTokenRefreshRequest())</pre><pre>  const { success } = yield race({<br>    success: take(userTokenRefreshSuccess().type),<br>    fail: take(userTokenRefreshFailure().type),<br>  })</pre><pre>  if (success) {<br>    console.log(&#39;token refreshed, retrying&#39;, monitoredAction.type)<br>    yield put(monitoredAction)<br>  } else {<br>    console.log(&#39;token refresh failed, logging out user&#39;)<br>    yield put(userLogoutRequest())<br>  }<br>}</pre><pre>...</pre><p>Token refresh is monitored too because the token could be corrupted or altered by a malicious code. In that case, there is nothing else to do but to log out the user and handle the problem somewhere else.</p><p>After successful token refresh, the failed action should be retried.</p><pre>  ...</pre><pre>  console.log(&#39;monitoring&#39;, monitoredAction.type, &#39;finished&#39;)<br>}</pre><p>When the action is retried the monitor returns and finishes it’s task although it will again be monitored by a new monitor. This could potentially create an endless loop but there is a solution for that too.</p><h4>Improvements</h4><p>This implementation of the monitor is already able to handle most of the cases in a web application, but there are some ways to make it even better.</p><ol><li>timeouts for waiting on SUCCESS and FAILURE actions</li><li>retry limits</li><li>plug &amp; play reusability in different projects</li><li><em>additional suggestions from the responses (maybe?)</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*qvuorrDgV4EF8kZGxmWUxw.gif" /><figcaption>I feel empowered</figcaption></figure><h3>Summary</h3><p>Web applications are slowly but surely getting more complex because users expect more. At the same time, product owners expect more for less time so it is essential to write smart and flexible code.</p><p>Sagas are a powerful tool that allows the developer to deliver that complex logic but make it very maintainable at the same time.</p><p>As said before, the code is available in this <a href="https://github.com/stjepangolemac/monitor-saga">repo</a>.</p><p><em>Let me know if you like this story below in the responses and make sure other people see it by clicking on them </em>👏<em>.</em></p><h3>Learn more</h3><ul><li><a href="https://blog.bitsrc.io/how-to-write-better-code-in-react-best-practices-b8ca87d462b0">How to write better code in React</a></li><li><a href="https://blog.bitsrc.io/11-javascript-utility-libraries-you-should-know-in-2018-3646fb31ade">11 Javascript utility libraries you should know</a></li><li><a href="https://blog.bitsrc.io/building-a-shared-ui-component-library-350b297a53a8">Building a UI component library</a></li></ul><h3>One last thing</h3><p>Bit’s component platform turns all the components and modules in your applications into an API you can use to build new things. Give it a try.</p><p><a href="https://bitsrc.io">Bit - Share and build with code components</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f5672303d7d" width="1" height="1"><hr><p><a href="https://blog.bitsrc.io/complex-app-logic-with-redux-and-redux-saga-write-an-authentication-monitor-2f5672303d7d">Complex App Logic With Redux And Redux Saga: Write an Authentication Monitor</a> was originally published in <a href="https://blog.bitsrc.io">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You are right!]]></title>
            <link>https://medium.com/@stjepan.golemac/you-are-right-ed55a1a8ae99?source=rss-512a4050aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed55a1a8ae99</guid>
            <dc:creator><![CDATA[Stjepan Golemac]]></dc:creator>
            <pubDate>Tue, 19 Jun 2018 07:55:31 GMT</pubDate>
            <atom:updated>2018-06-19T07:55:31.284Z</atom:updated>
            <content:encoded><![CDATA[<p>You are right! I wanted to be explicit here to make it more understandable but now I like it more your way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed55a1a8ae99" width="1" height="1">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Atomic Design With React And Bit: Simplify a Complex UI]]></title>
            <link>https://blog.bitsrc.io/simplify-complex-ui-by-implementing-the-atomic-design-in-react-with-bit-f4ad116ec8db?source=rss-512a4050aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4ad116ec8db</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Stjepan Golemac]]></dc:creator>
            <pubDate>Thu, 14 Jun 2018 14:38:31 GMT</pubDate>
            <atom:updated>2018-08-02T11:06:43.957Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to break down your UI’s complexity, easily manage it, catalog its components and compose them together.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LRtEYE6BX4jcWm0Sr_m1A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/v0zwX1aPlHI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Deva Darshan</a> on <a href="https://unsplash.com/new?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>The problem</h3><p>The world of frontend development is getting more complicated by the hour. There are new frameworks, tools, techniques, and user requirements every time I decide to read some news and tweets to catch up.</p><p>Finding a direction in that kind of quick and always changing environment is difficult. One way of finding a stable ground is organizing the code by some standard or a <strong>design system</strong>.</p><h3>Atomic Design</h3><p>It is a system that recognizes hierarchy, importance, type, and role of each and every component. The components are combined in a way that resembles the structure of our universe.</p><ul><li>atoms</li><li>molecules</li><li>organisms</li><li>templates</li><li>pages</li></ul><h4>Why</h4><p>The need for some kind of a design system appears when we start to get overwhelmed by the count of components on a project. In projects where there are a hundred or two hundred components, it is not easy to remember everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*ZS4ABYgdD0UGa1ZmUOFOuw.gif" /></figure><h4>Origin</h4><p>The mind behind this system is Brad Frost, and for those of you who want to learn more about it feel free to stop right here and first read his in-depth post on the subject. There is even a <a href="https://shop.bradfrost.com/collections/frontpage/products/atomic-design-print-ebook">book</a>.</p><p><a href="http://bradfrost.com/blog/post/atomic-web-design/">Atomic Design</a></p><h3>Example UI</h3><p>In my quest for the perfect UI to recreate, I could not find anything that satisfied me completely. This is the closest I could find.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*R_vfjcCvkrcJQdZCDkRp0Q.jpeg" /></figure><p>I will not try to pixel perfect it nor achieve the exact same layout. The goal here is to showcase the separation of components.</p><h4>Breakdown</h4><p>I do not consider this a deterministic process. I am certain there are better ways to decouple this UI into components but the essence is the same, make them more manageable. I will use the top-down approach.</p><ul><li><strong>one page</strong> - dashboard</li><li><strong>two templates</strong> - header and workspace</li><li><strong>many organisms </strong>- tools, time, map,…</li><li><strong>even more molecules </strong>- tool buttons, temperature info, feed items,…</li><li><strong>probably even more atoms </strong>- labels, icons, links, headings,…</li></ul><h4><strong>Cataloging</strong></h4><p>Making every component decoupled and available in an <strong>online catalog</strong> will make it easier for future developers to find and use them.</p><h3>Bit</h3><p>A component-as-a-service platform that enables components to be cloud-hosted, discoverable, versioned, isolated, and easily incorporated in other projects.</p><p><a href="https://bitsrc.io/">Bit - Share and build with code components</a></p><p>It solves common problems of managing component systems and saves developers from reinventing the wheel while increasing their productivity. Below is an example of a rendered component pushed to the Bit scope. For more information watch this <a href="https://www.youtube.com/watch?v=P4Mk_hqR8dU">video</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_n63DWa0X35Q5crRQk2ukg.png" /></figure><h4>Result</h4><p>In the end, I created 15 components that can be combined to build the view from the example UI. The charts are not included because they are out of the scope of this article. Components are cataloged and available on this <a href="https://bitsrc.io/stjepangolemac/atomic-design">link</a>. The repo that contains whole code can be found <a href="https://github.com/stjepangolemac/bit-atomic-design">here</a>.</p><p><a href="https://bitsrc.io/stjepangolemac/atomic-design">atomic-design. Javascript components by stjepangolemac.</a></p><p>After the development, it is really easy to make your own catalog of components. You just need to <a href="https://bitsrc.io/signup">sign up</a> on the bitsrc.io, then type in a few short commands and you are done.</p><pre># Navigate to the project directory and initialize Bit<br>$ cd project_dir</pre><pre>$ bit init<br>$ bit login</pre><pre># Add the components to the local scope<br>$ bit add src/components/atoms/*<br>  ...<br>$ bit add src/components/pages/*</pre><pre># Check if all components are added<br>$ bit status</pre><pre># Tag the version and upload the components to Bit<br>$ bit tag --all 1.0.0<br>$ bit export &lt;your_username&gt;.&lt;your_scope&gt;</pre><p>The result can be seen on this <a href="https://bitsrc.io/stjepangolemac/atomic-design">link</a>. That is a scope, think of it like a namespace for exported components. You can have as many scopes as you want, and you can make them private or public.</p><p>Let us see the &lt;Panel /&gt; component <a href="https://bitsrc.io/stjepangolemac/atomic-design/atoms/panel">here</a>. There is support for component documentation, testing, building, and compiling. You can even explore file structure and code.</p><pre>$ bit init<br>$ bit import &lt;your_username/&lt;your_scope/avatar-image \<br>  --path src/components/avatar-image</pre><p>You are now able to use these components in any future project by just importing the component. You do need to make sure the project that you are importing the components in supports bundling of resources used. For example, components from the link above import .css files.</p><p>You should definitely explore features that Bit offers like component <strong>rendering</strong>, <strong>testing</strong>, and <strong>documenting</strong>. The best place to start is the <a href="https://docs.bitsrc.io/docs/quick-start.html">official documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*uXIIGogL-Ss0BkNjbKqrQw.gif" /><figcaption>Pretty cool, right?</figcaption></figure><h3>Summary</h3><p><a href="https://bitsrc.io">Bit</a> is a refreshing new tool that makes it easier to manage <strong>modular</strong> and <strong>reusable</strong> components in a standardized way. Developers should focus on the project requirements and quality code delivery, they should not worry about the usage of their components in other projects or by other people.</p><p>Give Bit a try and if you have any problems feel free to ask for help on <a href="https://gitter.im/bit-src/Bit">Gitter channel</a> or send an email to <a href="mailto:team@bitsrc.io">team@bitsrc.io</a>.</p><h4>One last thing…</h4><p><em>Let me know if you like this story below in the responses and make sure other people see it by clicking on the </em>👏<em>.</em></p><h3>Learn more</h3><ul><li><a href="https://blog.bitsrc.io/11-react-component-libraries-you-should-know-178eb1dd6aa4">11 React UI Component Libraries You Should Know In 2018</a></li><li><a href="https://blog.bitsrc.io/how-to-write-better-code-in-react-best-practices-b8ca87d462b0">How To Write Better Code In React</a></li><li><a href="https://blog.bitsrc.io/11-javascript-utility-libraries-you-should-know-in-2018-3646fb31ade">11 Javascript Utility Libraries You Should Know In 2018</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4ad116ec8db" width="1" height="1"><hr><p><a href="https://blog.bitsrc.io/simplify-complex-ui-by-implementing-the-atomic-design-in-react-with-bit-f4ad116ec8db">Atomic Design With React And Bit: Simplify a Complex UI</a> was originally published in <a href="https://blog.bitsrc.io">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You are right, simple state that is of little or no importance to other components should be stored…]]></title>
            <link>https://medium.com/@stjepan.golemac/you-are-right-simple-state-that-is-of-little-or-no-importance-to-other-components-should-be-stored-bbf616623fb3?source=rss-512a4050aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbf616623fb3</guid>
            <dc:creator><![CDATA[Stjepan Golemac]]></dc:creator>
            <pubDate>Mon, 23 Apr 2018 09:35:05 GMT</pubDate>
            <atom:updated>2018-04-23T09:35:05.428Z</atom:updated>
            <content:encoded><![CDATA[<p>You are right, simple state that is of little or no importance to other components should be stored in component state. I did not mention that in this article but I agree that is a good practice.</p><p>There were attempts to handle the ui state in a ‘ui’ reducer in Redux but it had it’s flaws. Namespacing the states in that reducer increased the boilerplate code both in components and redux logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbf616623fb3" width="1" height="1">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step by step guide for writing awesome React components]]></title>
            <link>https://codeburst.io/step-by-step-guide-for-writing-awesome-react-components-210c6def902b?source=rss-512a4050aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/210c6def902b</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Stjepan Golemac]]></dc:creator>
            <pubDate>Thu, 18 Jan 2018 15:13:48 GMT</pubDate>
            <atom:updated>2018-06-19T07:56:27.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TRuG7tG0KrZJXKoFtHlSg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/73OZYNjVoNI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Stanley Dai</a> on <a href="https://unsplash.com/search/photos/writing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Descriptive and versatile checklist with must do’s and should do’s when conceptualizing sleek and professional React code</h4><p>Going through the process of learning and using React and Redux I came to a following conclusion - they are not hard to grasp but are fairly difficult to master. Both are pretty minimal when it comes to their API and that helps new users to churn out new components and even apps at an incredible pace. Nevertheless, that convenience degrades the average quality of React code.</p><p>Being the minimally opinionated library as it is, React allows a fair amount of maneuverability regarding the different approaches one can take. The consequence of that is the broad spectrum of available best practices for someone to apply. Some of those alleged best practices are not even good practices at all, and some of them are not compatible with one another. Best practices can depend on the tools and libraries you use, and they can be different relative to the type and purpose of the app.</p><p>The greatest difficulty I had and still have when searching for some additional valid knowledge is the lack of high quality and up-to-date materials. My goal here is to compile and organise in one place as many methods, concepts, and practices as my laziness allows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*2e37gUrR_nachrlEAokIzg.gif" /><figcaption>Show me what is React</figcaption></figure><h4>Pillars of creation</h4><p>High-quality React code rests on 5 pillars. It is not by chance a pillar and not a column, pole or a shaft. Pillar is defined as a <strong><em>slender</em></strong><em>, freestanding, vertical support (“Pillar.” The American Heritage® Dictionary of the English Language. Wordnik.com).</em></p><blockquote>The code should be <em>made as simple as possible, but not simpler. And it should document itself. And it should be fast. And that is it.</em></blockquote><p>There are 5 core principles (or pillars) of React components and they are:</p><ol><li><strong>Modularity</strong></li><li><strong>Reusability</strong></li><li><strong>Brevity</strong></li><li><strong>Flexibility</strong></li><li><strong>Efficiency</strong></li></ol><p>For every important thing that influences the usage of a best practice, there will be a ⻧ character (I do not know the origin nor the meaning of it, it just reminds me of a checkbox hanging on a sign). Afterwards, important concepts will be summarised along with the available ways to respect them.</p><h4>Modularity</h4><p>A proper way to write <strong>modular</strong> and composable Javascript code is to follow the principles of functional programming (⻧). A brief suggestion is to write functions wherever and whenever possible. More complex algorithms and processing should be handled with higher order functions (⻧) which take other functions as parameters or return them. That way the duplication of code is minimum and the organisation is maximum. Take a look at one helper function in the inferno-shared package from InfernoJS team:</p><pre>export function isNullOrUndef(o) {<br>  return isUndefined(o) || isNull(o)<br>}</pre><p>The function is composed of two functions that could again be composed of more functions. This prevents redundancy and visual complexity.</p><h4>Reusability</h4><p>As it is with every piece of code that is ever written, the shape of the implemented functionality must always adhere to some interchangeable format so that it can easily be replaced or <strong>reused</strong>. When it comes to React this principle can be fulfilled by grouping similar components or utility functions and extracting them to a separate git repo or npm package. A good example of this can once again be found in the work of the InfernoJS team.</p><pre>inferno-compat<br>inferno-component<br>inferno-create-class<br>inferno-create-element<br>inferno-devtools<br>inferno-hyperscript<br>inferno-mobx<br>inferno-redux<br>inferno-router<br>inferno-server<br>inferno-shared<br>inferno-test-utils<br>inferno-utils<br>inferno-vnode-flags<br>inferno</pre><p>Organising similar code in independent packages enables clean import paths, easier maintenance, and greater modularity. The downsides are reviewing changes and testing code which can become much more complex. Effects of those problems can be minimised by using <a href="https://github.com/lerna/lerna">Lerna</a>(⻧). Be sure to check <a href="https://webpack.js.org/configuration/resolve/#resolve-alias">Webpack aliasing feature</a> (⻧) for even shorter and more beautiful import paths.</p><h4>Brevity</h4><p>With the introduction of functional components in React 0.14 developers got the ability to write more concise and clear code (⻧). The type of component depends on the need to use component state (which is discouraged, use Redux) and lifecycle methods. Imagine a component that renders an image of a sloth. Now imagine the most verbose way to write it.</p><pre>class SlothImage extends React.Component {<br>  render() {<br>    return &lt;img src=&#39;sloth.gif&#39; alt=&#39;Pretty face&#39;&gt;<br>  }<br>}</pre><pre>export default SlothImage</pre><p>This code is completely correct and performant but can it be shorter? This component has no use of lifecycle methods.</p><pre>const SlothImage = props =&gt; {<br>  return &lt;img src=&#39;sloth.gif&#39; alt=&#39;Pretty face&#39;&gt;<br>}</pre><pre>export default SlothImage</pre><p>Two lines have been spared by converting the class component to the functional component. What if the source and alt text are externally defined?</p><pre>const SlothImage = props =&gt; {<br>  return &lt;img src={props.source} alt={props.alternativeText}&gt;<br>}</pre><pre>export default SlothImage</pre><p>The amount of lines is unchanged but the total number of characters is greater. Heard of JavaScript destructuring (⻧)?</p><pre>const SlothImage = ({ source, alternativeText }) =&gt; {<br>  return &lt;img src={source} alt={alternativeText}&gt;<br>}</pre><pre>export default SlothImage</pre><p>That is better but it is not enough. Let us rename the props to their respective &lt;img&gt; counterparts and export the component in the same line.</p><pre>/*<br>The props should now be built like this:<br>{<br>  src: &#39;sloth.gif&#39;,<br>  alt: &#39;Pretty face&#39;,<br>}<br>*/</pre><pre>export default props =&gt; &lt;img {...props}&gt;</pre><p>The dots are called a spread operator (⻧). One line is short enough but most of the real world components are not this simple. Remember, the goal is to reduce the number of characters, not newlines. My personal taste for writing more complex components is as follows:</p><pre>export default ({<br>  separateNext: underline,<br>  rightComponent,<br>  onRightComponentClick,<br>  ...rest: imgProps<br>}) =&gt; {<br>  return (<br>    &lt;Row<br>      <em>underline<br>      actionComponent</em>={rightComponent}<br>      <em>onActionClick</em>={onRightComponentClick}<br>    &gt;<br>      &lt;SlothImage {...imgProps} /&gt;<br>    &lt;/Row&gt;<br>  )<br>}</pre><p>If I could pick one rule in writing React components it would be exceeding the 80 characters mark (⻧) in a single line. When dealing with more than few properties it is always a good idea to format them one below another and to properly indent them. Using destructuring along with renaming and the rest operator (⻧) is a good way to save some keystrokes.</p><h4>Flexibility</h4><p>If we want the components to be reusable, they need to be able to fit in different contexts and visual environments. That implies having different shape and style dependent on the parents or surrounding children. The component that renders a text input for entering an amount of money could be used like this:</p><pre>&lt;TextInput<br>  wide<br>  required<br>  suffix={&lt;DollarSign /&gt;}<br>&gt;<br>  43<br>&lt;/TextInput&gt;</pre><p>The logic for achieving the correct behavior of this component is not too complex. The checks for boolean props are oneliners and rendering the suffix is a matter of injecting it in the right place. But the over need for flexibility and customisation may complicate the component to the point where it has several hundred lines of code. The sign of overcomplication is the usage of “<em>enum</em>” like props or having too many props.</p><pre>&lt;TextInput<br>  required<br>  width=&#39;col-6&#39;<br>  height=&#39;xlarge&#39;<br>  bgColor=&#39;#a4a4a4&#39;<br>  type=&#39;primary&#39;<br>  suffix=&#39;dollar&#39;<br>&gt;<br>  1337<br>&lt;/TextInput&gt;</pre><p>Every component should have a single responsibility (⻧) and a reasonable amount of flexibility. If the code is too complex, break it down to several components.</p><h4>Efficiency</h4><p>User experience greatly depends on the responsiveness and snappy interaction which must be the priority when building (progressive) web apps. One of the things that can slow down transitions and navigation is unnecessarily iterating over arrays, especially if the app contains long tables and lots of repeating elements. Let’s suppose we need to render only short strings in spans.</p><pre>const arr = [&#39;foo&#39;, &#39;bazzzz&#39;, &#39;bartender&#39;, &#39;qux&#39;]</pre><pre>const spans = arr<br>  .filter(entry =&gt; entry.length &lt;= 3)<br>  .map(entry =&gt; &lt;span&gt;{entry}&lt;/span&gt;)</pre><p>This way there are two loops to do a simple rendering. A great way to get two times faster execution is to, guess once, shorten the number of loops twofold.</p><pre>const spans = arr.reduce((acc, curr) =&gt; {<br>    return curr.length &lt;= 3 ? [...acc, &lt;span&gt;{curr}&lt;/span&gt;] : acc<br>},[])</pre><p>The reduce method (⻧) on the Array object is very powerful since it allows processing the entries before accumulating them by some rule.</p><p>Performance can be even greatly impacted by unnecessary re-renders of complex React components. Every change in the props triggers the rendering process that can be CPU intensive for complex components. To the rescue comes <em>shouldComponentUpdate</em> (⻧) lifecycle hook. If the change in some prop does not need to trigger rendering it can be written like this:</p><pre>class Example extends React.Component {<br>  ...<br>  shouldComponentUpdate(nextProps, nextState) {<br>    return nextProps.foo !== this.props.foo<br>  }<br>  ...<br>}</pre><p>When this hook returns true the component will be re-rendered, and if it returns false it will not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*uL5cRuthS6m0UVPWD-DZGw.gif" /><figcaption>I gotta go try all of this</figcaption></figure><h4>Important concepts sorted by magic (⻧)</h4><ul><li>Functional programming</li><li>shouldComponentUpdate</li><li>Higher order functions</li><li>Functional components</li><li>Lerna</li><li>Webpack resolve.alias</li><li>Destructuring</li><li>Spread operator</li><li>Rest operator</li><li>80 characters</li><li>Single responsibility</li><li>Array.reduce</li></ul><h4>One last thing…</h4><p><em>Let me know if you like this story below in the responses and make sure other people see it by clicking on the </em>👏<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=210c6def902b" width="1" height="1"><hr><p><a href="https://codeburst.io/step-by-step-guide-for-writing-awesome-react-components-210c6def902b">Step by step guide for writing awesome React components</a> was originally published in <a href="https://codeburst.io">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How would you handle the situation where the user entity sometimes contains a subset of user…]]></title>
            <link>https://medium.com/@stjepan.golemac/how-would-you-handle-the-situation-where-the-user-entity-sometimes-contains-a-subset-of-user-511f07183bf2?source=rss-512a4050aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/511f07183bf2</guid>
            <dc:creator><![CDATA[Stjepan Golemac]]></dc:creator>
            <pubDate>Tue, 05 Dec 2017 11:41:01 GMT</pubDate>
            <atom:updated>2017-12-05T11:41:01.641Z</atom:updated>
            <content:encoded><![CDATA[<p>How would you handle the situation where the user entity sometimes contains a subset of user properties? For example, when fetching a filtered list of users that contains only ids and fullnames.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=511f07183bf2" width="1" height="1">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You made quite an impressive list right there.]]></title>
            <link>https://medium.com/@stjepan.golemac/you-made-quite-an-impressive-list-right-there-e729ac374866?source=rss-512a4050aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e729ac374866</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Stjepan Golemac]]></dc:creator>
            <pubDate>Sat, 29 Apr 2017 10:34:51 GMT</pubDate>
            <atom:updated>2017-04-29T10:34:51.839Z</atom:updated>
            <content:encoded><![CDATA[<p>You made quite an impressive list right there. It will take some time to read it through but I think you’re doing a great service to the React-Redux community.</p><p>I will surely keep in mind to give you some feedback on that topic, maybe even propose something different when the time is right. Anyway, thank you for your response.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e729ac374866" width="1" height="1">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First of all, thank you for your detailed response.]]></title>
            <link>https://medium.com/@stjepan.golemac/first-of-all-thank-you-for-your-detailed-response-144785c75368?source=rss-512a4050aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/144785c75368</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Stjepan Golemac]]></dc:creator>
            <pubDate>Thu, 27 Apr 2017 20:44:30 GMT</pubDate>
            <atom:updated>2017-04-27T20:44:30.856Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, thank you for your detailed response. You are exactly right about defining a public interface of Redux modules. Every module should have a single entry point from which the appropriate parts can be imported in a more controlled fashion.</p><p>The motivation behind redux-constants-builder was indeed the boilerplate of redux API middleware constants. It is a small step towards more compact code. Builders for reducers and sagas could substantially shorten the boilerplate and I have some ideas about that too. I am still conceptualizing a way to use all these builders to make a redux module builder that could maybe fit an entire logic of a module in one file.</p><p>I did see redux-io before a couple of weeks on your Shoutem documentation and put it on my “must try” list. I am making some plans to build a relatively simple React Native app using Shoutem and redux-io, which seem really amazing. The only question I have for redux-io is how would you handle authentication?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=144785c75368" width="1" height="1">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slashing down the linescraper one domain at a time]]></title>
            <link>https://medium.com/@stjepan.golemac/slashing-down-the-linescraper-one-domain-at-a-time-e7b546250a22?source=rss-512a4050aac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b546250a22</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Stjepan Golemac]]></dc:creator>
            <pubDate>Wed, 26 Apr 2017 21:33:26 GMT</pubDate>
            <atom:updated>2017-04-27T19:21:58.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eTIfaIG8wm5pYV_X9qgkg.jpeg" /><figcaption><em>And many strokes though with a little axe hew down and fell the hardest-timbered oak.</em></figcaption></figure><h4>Reducing the Redux boilerplate by domain driven modularization of store management logic.</h4><p>I started using React and Redux a couple of months ago and after going through the basic concepts I immediately <strong>fell in love</strong>. It took one relatively complex app to realize how much boilerplate I needed to write. It soon became apparent that without some kind of <strong>reorganization</strong> of logic and file structure, maintenance and extension will become tiresome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*J-U30HPYHDkWU0Hh91vwEw.gif" /><figcaption>I am all ears…</figcaption></figure><p>After a couple of days of researching and thinking about ways to reduce the code, I conceived a template. The biggest concern I wanted to avoid was the <strong>towering height</strong> of Redux-related folders like constants and actions and the long import paths.</p><p><strong>DISCLAIMER</strong>: The packages which I use are not obligatory by any means and these tips can be used with virtually any selection of tools. This disclaimer is mostly related to the selectors and sagas below.</p><h4>Grouping files by function</h4><p>Most guides and tutorials regarding React and Redux on the web are following this folder layout:</p><pre>actions/<br>  |-- codes.js<br>  |-- locations.js<br>  |-- partners.js<br>  |-- users.js<br>constants/<br>  |-- codes.js<br>  |-- locations.js<br>  |-- partners.js<br>  |-- users.js<br>reducers/<br>sagas/<br>selectors/</pre><p>This folder structure is commonly known as “<em>Rails-style</em>” and it groups the files based on their function which is not per se a bad thing. The problem appears when you have tens of files grouped together and every action requires you to skim the list in a quest for the right file.</p><p>Making it even worse, import paths are always crossing several levels of folders which make imports fat and importing <strong>cumbersome</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*OZxieWtrbGicN7sMEd9KbA.gif" /><figcaption>This is not going to work…</figcaption></figure><h4>Domain driven modularization</h4><p>What if we could group files by their respective “<em>departments</em>”? For example, let’s put all <em>users</em> related files in one folder and point out some advantages of this approach.</p><pre>users/<br>  |-- actions.js<br>  |-- constants.js<br>  |-- reducer.js<br>  |-- saga.js<br>  |-- selectors.js</pre><p>At first glance, nothing special happened but let’s address aforementioned problems and see what is different.</p><ul><li><strong>File count — </strong>folders are now easier to skim through or analyze and they are using less vertical space, which means better use of screen real estate</li><li><strong>Import paths</strong> — importing now takes less horizontal space because all related files are in the same folder, which means no more figuring out how many slashes or dots is enough</li></ul><p>Depending on the size and complexity of your project, it may already seem considerably easier to maintain and extend the codebase. But, what if there were additional improvements?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*bBPXsLa9GmnSpMu8578zZg.gif" /><figcaption>Count me in…</figcaption></figure><h4>Bundling the domain</h4><p>Organizing the code like this allows us to define an index file that could import all those specific files, and then export them from a <strong>single point</strong>. For example, let’s take <em>users</em> domain and bundle it into one file.</p><pre>users/<br>  |-- actions.js<br>  |-- constants.js<br>  |-- reducer.js<br>  |-- saga.js<br>  |-- selectors.js<br>  |-- <strong>index.js</strong></pre><p>Now, all remaining files need to be imported into the index file and afterwards exported.</p><pre>// <strong>index.js</strong></pre><pre>import * as constants from &#39;./constants&#39;<br>import * as actions from &#39;./actions&#39;<br>import * as selectors from &#39;./selectors&#39;</pre><pre>import reducer from &#39;./reducer&#39;<br>import saga from &#39;./saga&#39;</pre><pre>export {<br>  constants,<br>  actions,<br>  selectors,<br>  reducer,<br>  saga<br>}</pre><p>We can make this even shorter by directly exporting imported modules. The downside of this approach is losing the grouping of imports.</p><pre>export * from &#39;./constants&#39; // BAD<br>export { default as reducer } from &#39;./reducer&#39; // GOOD</pre><p><em>EDIT: Exporting and renaming the import is actually possible if you are willing to use </em><a href="https://babeljs.io/docs/plugins/transform-export-extensions/"><em>Babel export extensions transform</em></a><em>. Thanks to </em><a href="https://medium.com/u/81d466b1345a"><em>Matija Marohnić</em></a><em> for pointing this out to me!</em></p><p>This way, when you need something related to the <em>users</em> domain, you always import from the <strong>same path</strong>. It’s not uncommon to import both action creators and selectors at the same time.</p><pre>import<br>  actions as usersActions,<br>  selectors as userSelectors<br>} from &#39;../../redux/users&#39;</pre><h4>Composing React components</h4><p>The index file can be used for all sorts of wiring and enwrapments of React components too. This is exceptionally useful if the component is connected to the part of Redux state and has constants, action creators, or requires an async action to be called. The structure is the same with the addition of the component definition.</p><pre>// containers/TodoList/<strong>index.js</strong></pre><pre>import { connect } from &#39;react-redux&#39;</pre><pre>import TodoList from &#39;./todolist&#39;</pre><pre>import * as constants from &#39;./constants&#39;<br>import * as actions from &#39;./actions&#39;<br>import * as selectors from &#39;./selectors&#39;</pre><pre>import reducer from &#39;./reducer&#39;<br>import saga from &#39;./saga&#39;</pre><pre>const connectedTodoList = connect(<br>  state =&gt; {<br>    return {<br>      todos: selectors.todos(state)<br>    } <br>  },<br>  dispatch =&gt; {<br>    return {<br>      getTodos: () =&gt; dispatch(actions.get.try())<br>    }<br>  }<br>)(TodoList)</pre><pre>export default connectedTodoList<br>export {<br>  constants,<br>  actions,<br>  selectors,<br>  reducer,<br>  saga<br>}</pre><h4>Conclusion</h4><p>Not everyone will appreciate the granularity of control and choice available while writing React + Redux apps. However, if utilized effectively it can lead to surprisingly <strong>sleek and organized</strong> code.</p><p>I am currently experimenting with builders for Redux-related code and if I succeed in making the code short enough, putting all of this in a single, well-organized file may be a plausible action. The builder for constants can already be tested.</p><p><a href="https://www.npmjs.com/package/redux-constants-builder">redux-constants-builder</a></p><p>Feel free to <strong>try it</strong> and leave your suggestions, comments and ideas!</p><p>I hope this article was helpful and that it would spark some new ideas about code structure in React + Redux apps. Stay tuned for my future efforts to reduce the Redux boilerplate!</p><h4>One last thing…</h4><p><em>Let me know if you liked this story down in the responses and make sure other people see it by clicking on the ❤.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b546250a22" width="1" height="1">]]></content:encoded>
        </item>
    </channel>
</rss>