<?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 Jalal Fathi on Medium]]></title>
        <description><![CDATA[Stories by Jalal Fathi on Medium]]></description>
        <link>https://medium.com/@jalalio?source=rss-7aed01b0bfec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*n_O69PIlNWbB-phV.jpeg</url>
            <title>Stories by Jalal Fathi on Medium</title>
            <link>https://medium.com/@jalalio?source=rss-7aed01b0bfec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 17:43:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jalalio/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[Why I use double equal null in JavaScript]]></title>
            <link>https://medium.com/@jalalio/why-i-use-double-equal-null-in-javascript-1ee4e2f0aca4?source=rss-7aed01b0bfec------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ee4e2f0aca4</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jalal Fathi]]></dc:creator>
            <pubDate>Mon, 14 Oct 2019 18:01:48 GMT</pubDate>
            <atom:updated>2019-10-22T12:14:23.236Z</atom:updated>
            <content:encoded><![CDATA[<h4>What the number 0, an empty string, undefined and null values have in common? Nothing really, I would say.</h4><p>In the majority of codebases you will see statements as below:</p><pre>if (this.age) {<br>  this.postUpdate(age);<br>}</pre><p>And why not. They look good and even encourage sexy one-liners:</p><pre>if (!this.age) return;</pre><p>These checks are fruitful soil for bugs of any kind. Read why.</p><h3>Let’s start with some basics</h3><p>To understand why above statements are usually not the way to go, we need to understand the results of below expressions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85b3c0bcc0251662133dea5642eeb518/href">https://medium.com/media/85b3c0bcc0251662133dea5642eeb518/href</a></iframe><p>I assume that in most of your use cases you actually want to check a variable against <em>null</em> and <em>undefined</em> values and not against an empty string or the number 0.</p><pre>if (!this.variable) {<br>  // matches: &quot;&quot;, 0, undefined, null<br>}</pre><pre>if (this.variable == null) {<br>  // matches undefined, null<br>}</pre><p>I get it,</p><pre>if (variable == null)</pre><p>does not look that sexy — but trust me, once you start applying it as your default way, there is no way back.</p><p>I gathered some examples which cause unexpected behaviour or are simply bugs.</p><h3>Example 1</h3><p>This function returns the function result of the <em>trueFn</em> invocation if an expression is defined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc3b66c9aa307188222a783e4cb001eb/href">https://medium.com/media/cc3b66c9aa307188222a783e4cb001eb/href</a></iframe><h4>Problem</h4><p>Passing in an empty string “” or 0 number will result in a <em>falseFn </em>invokation<em>. </em>You may imagine, that passing in 0 or “” can be a very common use case in this scenario.</p><p><strong>Fails</strong></p><pre>// age=0 should be a valid option<br>when(age, () =&gt; &#39;Her age is:&#39;, () =&gt; &#39;Loading&#39;);</pre><pre>// if bio is an empty string, then the input should be empty as well<br>when(bio, () =&gt; bio, () =&gt; &#39;Loading&#39;);</pre><h4>Solution</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0b1438d38356d40a4d87bf0304cf95c/href">https://medium.com/media/d0b1438d38356d40a4d87bf0304cf95c/href</a></iframe><h3>Example 2</h3><p>This is an event listener callback gets called whenever the value of an input changes. The intention of the developer was not to exclude 0 and empty values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/065d94ec289b4aaaec36adb450d810d0/href">https://medium.com/media/065d94ec289b4aaaec36adb450d810d0/href</a></iframe><p><strong>Fails</strong></p><pre>// Both were allowed values</pre><pre>_valueChanged(0)<br>_valueChanged(&quot;&quot;)</pre><h4>Solution</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97772435ac1748470a3f014291b55146/href">https://medium.com/media/97772435ac1748470a3f014291b55146/href</a></iframe><h3>Example n</h3><p>Every other month I find bugs related to the usual way of checking variables. I’ll keep adding them if time allows.</p><p>In a rising number of popular JavaScript libraries, you’ll see the double equal null checks in their codebase. Underscore, Less and even JQuery apply this principle. Linters allow the use of loose equality checks when it comes to null. See also AirBnB’s best practices <a href="https://github.com/airbnb/javascript/blob/57ff032b0740ba2a46af4bc40cf5638a3e62a365/packages/eslint-config-airbnb-base/rules/best-practices.js#L40">https://github.com/airbnb/javascript/blob/57ff032b0740ba2a46af4bc40cf5638a3e62a365/packages/eslint-config-airbnb-base/rules/best-practices.js#L40</a></p><p>Strict type checking might be another option to do those checks. However, I believe that in at least 80% of the the times we write this code unconciously and do not think of all possible scenarios. If your default way of checking against defined values is ==null, then you should be fine in most cases.</p><p>See also <a href="http://adripofjavascript.com/blog/drips/equals-equals-null-in-javascript.html">http://adripofjavascript.com/blog/drips/equals-equals-null-in-javascript.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ee4e2f0aca4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[a !== a]]></title>
            <link>https://medium.com/@jalalio/a-a-607a63e9cb82?source=rss-7aed01b0bfec------2</link>
            <guid isPermaLink="false">https://medium.com/p/607a63e9cb82</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nan]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Jalal Fathi]]></dc:creator>
            <pubDate>Fri, 15 Jun 2018 13:19:20 GMT</pubDate>
            <atom:updated>2019-10-14T11:32:46.724Z</atom:updated>
            <content:encoded><![CDATA[<h4>too good to be true?</h4><blockquote>The actual heading should be: A short story about the weird parts of NaN</blockquote><p>NaN in JavaScript stands for “Not a Number”. The type of NaN is surprisingly Number. Which is weird because it is used to define something which isn’t a number.</p><p>typeOf(NaN); // &quot;number&quot;</p><p>It is used for instance for a result of a bad calculation.</p><p>var a = 3 * &quot;jalal&quot;; // NaN</p><p>The most confusing part aboutNaN is that NaN compared to anything else is always false!</p><p>NaN == false; // false</p><p>NaN == true; // false</p><p>An even compared to itself equals always false.</p><p>NaN == NaN; // false</p><p>NaN === NaN; // false</p><p>This raises one question:</p><h3>How to check if a variable is NaN?</h3><p>There is a function in JavaScript called isNaN(), but it has, unfortunately, some issues on its own.</p><p>Let’s go through some examples:</p><p>isNaN(NaN); // true</p><p>That worked!</p><p>isNaN(1); // false because 1 is a number</p><p>This is also not surprising!</p><p>isNaN(&#39;1&#39;); // false</p><p>This worked too because <strong>isNaN</strong> <strong>coerces</strong> <strong>the passed in parameter</strong> and then checks if it is not a number.</p><p>isNaN(&#39;a&#39;); // true because &#39;a&#39; is not a number</p><p>Again, an implicit coercion is happening here. isNaN tries to convert the parameter into a number. The result of this effort having ‘a’ as a parameter is NaN:</p><p>Number(&#39;a&#39;); // NaN</p><p>parseInt(&#39;a&#39;); // NaN</p><p>Number(&#39;1&#39;); // 1</p><p>This is why isNaN(&#39;a&#39;) returns true. It’s similar to isNaN(Number(&#39;a&#39;)) .</p><p>So basically the <strong>isNaN function is useless unless</strong> you are 100% certain that the passed in parameter is supposed to be a number.</p><p><strong>Again, how to check if a variable is NaN?</strong></p><p>We mentioned before that NaN is the only JavaScript variable that returns false if it is compared to itself. We can make use of that!</p><p>var a = 3 * &#39;jalal&#39;; // a = NaN</p><p>if (a !== a) console.log(&#39;A is NaN&#39;); // a !== a equals to true</p><p>This is the only way (I am aware of) to certainly check if a variable is NaN.</p><p>You can imagine that those weird parts are important to know because they are fruitful soil for bugs of any kind.</p><blockquote><strong>Jalal Fathi</strong> is freelance software developer and startup founder. Passionate about web technologies and in love with JavaScript. <a href="https://jalal.io/">Learn more</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=607a63e9cb82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic OG-Tags in your statically Firebase hosted (Polymer) web app]]></title>
            <link>https://medium.com/@jalalio/dynamic-og-tags-in-your-statically-firebase-hosted-polymer-app-476f18428b8b?source=rss-7aed01b0bfec------2</link>
            <guid isPermaLink="false">https://medium.com/p/476f18428b8b</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[meta-tags]]></category>
            <category><![CDATA[polymer]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <category><![CDATA[dynamic-og-tags]]></category>
            <dc:creator><![CDATA[Jalal Fathi]]></dc:creator>
            <pubDate>Sun, 21 Jan 2018 13:11:12 GMT</pubDate>
            <atom:updated>2018-06-15T13:20:01.173Z</atom:updated>
            <content:encoded><![CDATA[<p>Be an OG. <a href="https://www.urbandictionary.com/define.php?term=original+gangster">Original Gangster</a> or <a href="http://ogp.me/">Open Graph</a> Tagger.</p><h3>The Problem.</h3><p>You finished developing your web app, on-boarded the first people and you are now focusing on growing your user base a bit. That’s the moment you realise, holy shi…, how can I create dynamic OG-Tags so Facebook and other Platforms show different content when sharing different URLs of your page. You research a bit and you figure out that this is not possible with statically hosted websites because Javascript does not get executed by these crawlers.</p><p>You stumble upon prerender.io. You think, really, do I have to do this? You start playing around with your NGINX config files and figure out how to proxy requests from social bots to prerender.io. You kind of hate it.</p><p>Your next app is hosted on Firebase. You (again) do not think about the importance of dynamic Open Graph Meta Tags. You onboard the first users and start focusing on growth. You remember prerender.io. You think about server config files. You start scratching your head. You think f***. I cannot configure my Firebase server. You start crying. Crying is good for you. You gotta feel it to heal it.</p><h3>The Solution.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*tj1iDacSDnlLWYN0PmSkrg.png" /><figcaption>He could not care less about config files.</figcaption></figure><p>The solution comes with using <a href="https://firebase.google.com/docs/functions"><strong>Firebase Functions</strong></a><strong>,</strong> and it’s quite simple. <br>Just need to add a <a href="https://firebase.google.com/docs/functions/http-events">http trigger</a>, analyse the request, replace your meta tags and return the modified index file. Thats about it.</p><pre>exports.host = functions.https.onRequest((req, res) =&gt; {<br>  // do your stuff and return the index.html file<br>});</pre><p>Let’s take a look at an actual implementation.</p><h4>1. Add placeholder for dynamic meta tags</h4><p>index.html</p><p>Let’s add some placeholder and replace them afterward with dynamic meta tags in the Firebase function.</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;</pre><pre>    &lt;!-- <br>    Gets replaced by URL specific meta tags via Firebase Functions<br>    --&gt;<br>    &lt;meta name=&quot;functions-insert-dynamic-meta&quot;&gt;<br>    &lt;meta name=&quot;functions-insert-dynamic-og&quot;&gt;<br></pre><pre>    &lt;link rel=&quot;import&quot; href=&quot;src/my-app.html&quot;&gt;<br>  &lt;/head&gt;</pre><pre>  &lt;body&gt;<br>    &lt;my-app&gt;&lt;/my-app&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>We can now reference these functions-insert-dynamic-xyz meta tags in our Firebase function. But the main reason for me to use a placeholder and not just reference &lt;/head&gt;, is that they remind me that there is something happening with this file before it gets served.</p><h4>2. Copy index.html into our functions folder</h4><p>build/index.html copy tofunctions/hosting/index.html</p><p>We need to be able to reference the index.html in our functions. For that, we create a functions/hosting folder and paste the index file in there. <br>I do that automated while building my app. You may include the build step in yourgulpfile.js or whatever you are using to build the app. I just add below copy action into my package.json file so I can run npm run build.</p><pre>&quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;polymer build &amp;&amp; cp build/es5-bundled/index.html functions/hosting/&quot;,</pre><pre>},</pre><h4>2. Add the function</h4><p>functions/index.js</p><p>In this example, we want different meta tags with each organisation.</p><pre>example.com/ =&gt; Default meta tags<br>example.com/xyz/ =&gt; Default meta tags</pre><pre>example.com/organisation/red-cross =&gt; Check database for the red cross organisation and return specific meta tags</pre><p>We also only want to make the effort to replace the meta tags if the user agent requesting the page is a bot. Otherwise, we don’t care much and just return the original index file with some default meta tags.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/002175134d6753de7f6db384399f2acb/href">https://medium.com/media/002175134d6753de7f6db384399f2acb/href</a></iframe><h4>3. Add rewrites</h4><p>firebase.json</p><p>Now we need to make sure, that on every request our host function gets called. For that, we need to add a rewrite entry to our firebase.json file.</p><pre>&quot;hosting&quot;: {<br>  &quot;rewrites&quot;: [{<br>    &quot;source&quot;: &quot;/**&quot;,<br>    &quot;function&quot;: &quot;host&quot;<br>  }]<br>},</pre><p>That’s it. Deploy the app and enjoy the magic.</p><p>Thanks for reading.</p><blockquote><strong>Jalal Fathi</strong> is freelance software developer and startup founder. Passionate about web technologies and in love with Polymer. <a href="https://jalal.io/">Learn more</a> about how he can help you to create your next digital product. He works wherever he wants and tries to catch a good swell wherever he can. He wrote this bio by himself while writing in third person.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=476f18428b8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step 3: How to make async API calls in a Polymer 2 app using Redux Thunk middleware]]></title>
            <link>https://medium.com/@jalalio/step-3-how-to-make-async-api-calls-in-a-polymer-2-app-using-redux-thunk-middleware-c71d596c2005?source=rss-7aed01b0bfec------2</link>
            <guid isPermaLink="false">https://medium.com/p/c71d596c2005</guid>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[polymer]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jalal Fathi]]></dc:creator>
            <pubDate>Fri, 19 Jan 2018 19:36:21 GMT</pubDate>
            <atom:updated>2018-12-12T10:39:12.161Z</atom:updated>
            <content:encoded><![CDATA[<h4>A 3 step tutorial on how to integrate Redux into a larger Polymer 2 app showcasing a working example.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*wlJVyw4w9KNcBiGJ0vzdCA.png" /></figure><p><strong>Step-3</strong> shows how to extend our app in order to call a Firebase (or any other) API endpoint. If you are not familiar with using Redux in a Polymer app, go back to <a href="https://medium.com/@jalalio/step-1-how-to-use-redux-with-polymer-2-7bcfaee6fdb3">Step-1</a>!</p><pre>// If you want to clone this tutorial:</pre><pre>git clone <a href="https://github.com/JaySunSyn/ReduxTodo.git">https://github.com/JaySunSyn/ReduxTodo.git</a></pre><p>and make sure to uncomment the step-3 import in index.html</p><pre>&lt;!-- &lt;link rel=&quot;import&quot; href=&quot;/step-1/my-app.html&quot;&gt; --&gt;<br>&lt;!-- &lt;link rel=&quot;import&quot; href=&quot;/step-2/my-app.html&quot;&gt; --&gt;<br>&lt;link rel=&quot;import&quot; href=&quot;/step-3/my-app.html&quot;&gt;</pre><p>Let’s create one more file to include our middleware logic. Our file structure looks now like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*izlUX7YLFyKvLJ9aYkZ7kQ.png" /></figure><h3>Install dependencies</h3><pre>npm install — save redux-thunk</pre><h3>Redux Thunk</h3><blockquote>Redux Thunk <a href="https://github.com/reactjs/redux/blob/master/docs/advanced/Middleware.md">middleware</a> allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.</blockquote><p><strong>What problem do we try to solve with Redux Thunk?</strong></p><p>We cannot use async functions in our reducers simply because of the way they work. As we already know, <em>a reducer does not modify the current state</em>. It takes the previous state and returns the next state. So waiting for a promise to resolve would not work here …</p><p><strong>Could we solve that </strong>differently<strong>?</strong></p><p>Yes, we can! But we shouldn’t!<br>In our actions, we could trigger an API call and just return the previous state. After we receive the response, we could dispatch an action which would update the state based on the response.</p><pre>// DON&#39;T DO THIS</pre><pre>(state, action) =&gt; {<br>    if (action.type === &#39;CALL_API&#39;) {<br>        callApi().then(result =&gt; {<br>            store.dispatch({type: &#39;UPDATE_STATE&#39;, data: result});<br>        })<br>    }</pre><pre>    // implement &#39;UPDATE_STATE&#39;</pre><pre>    return state;</pre><pre>}</pre><p>The action is not pure anymore and can have side effects. I think Redux wouldn’t even allow it. See source code <a href="https://github.com/reactjs/redux/blob/master/src/utils/isPlainObject.js#L5">here</a>.</p><p><strong>What’s a middleware?</strong></p><p>In short, a middleware runs in the Store after we call this.dispatch() and before the dispatched action reaches the reducer. (Read the <a href="https://redux.js.org/docs/advanced/Middleware.html">docs</a> for a more in-depth explanation.)</p><p>This allows us to hijack the dispatch, call an api endpoint, wait for the response, and dispatch the action afterward with the data of the response!</p><h3>Implementation</h3><p>redux-middleware.html</p><p>Let’s take a look at our code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd6a59337b28100e6b8884aed0027b42/href">https://medium.com/media/bd6a59337b28100e6b8884aed0027b42/href</a></iframe><p>Every time we call dispatch() in our app, callAPIMIddleware gets called. Mostly, we just pass the action on to the reducer and do nothing here. We check if the action has a ‘types’ attribute and if not, we pass it on. If it has a ‘types’ attribute, we assume that we do want to call an API.</p><p>Let’s take a look at how our add (or addTodo) <strong>action</strong> has changed to understand a bit what we are doing here …</p><pre>const addTodo = (todo) =&gt; {<br>    const params = {<br>        method: ‘POST’,<br>        body: JSON.stringify({text: todo}),<br>    };</pre><pre>    return {<br>       // Types of actions to emit before and after<br>       types: [‘ADD_TODOS_REQUEST’, ‘ADD_TODOS_SUCCESS’, ‘ADD_TODOS_FAILURE’],</pre><pre>      // Perform the fetching:<br>      callAPI: () =&gt; fetch(&#39;https://example.com/api/todos&#39;, params)<br>    };<br>};</pre><p>We return an Object with 3 types.</p><p>ADD_TODO_REQUEST: We dispatch that one before we call the API.</p><p>ADD_TODO_SUCCESS: When the API call was successful we dispatch that type and add the response as a JSON Object to the action.</p><p>ADD_TODO_FAILURE: You guessed it, if something goes wrong.</p><p>Our <strong>reducers</strong> are pretty much straight forward. When adding a Todo, we do not need to do much further and just return the previous State.</p><pre>case &#39;ADD_TODOS_SUCCESS&#39;:<br>    console.log(&#39;ADD_TODOS_SUCCESS&#39;);<br>    return state;</pre><p>Let’s only take a quick look at our LOAD_TODOS_SUCCESS reducer which gets called by our fetchTodo() action. See <a href="https://github.com/JaySunSyn/ReduxTodo/blob/master/step-3/redux/redux-actions.html#L6">here</a>.</p><pre>case &#39;LOAD_TODOS_SUCCESS&#39;:<br>    todos = Object.keys(action.json).map(k =&gt; {<br>        return {<br>            text: action.json[k].text,<br>            key: k,<br>        };<br>    });</pre><pre>    return Object.assign({}, state, {todos: todos});</pre><p>We only do some normalisation and return a new state with the updated todos.</p><p>More questions? <a href="https://github.com/JaySunSyn/ReduxTodo/">Take a look at and try our working example on GitHub!</a></p><p>That’s all for now. Thanks for reading.</p><blockquote><strong>Jalal Fathi</strong> is freelance software developer and startup founder. Passionate about web technologies and in love with Polymer. <a href="https://jalal.io/">Learn more</a> about how he can help you to create your next digital product. He works wherever he wants and tries to catch a good swell wherever he can. He wrote this bio by himself while writing in third person.</blockquote><ul><li><a href="https://medium.com/@jalalio/step-1-how-to-use-redux-with-polymer-2-7bcfaee6fdb3">Step 1: How to use Redux with Polymer 2</a></li><li><a href="https://medium.com/@jalalio/step-2-how-to-structure-larger-polymer-2-apps-with-redux-reselect-f588e64a191a">Step 2: How to structure larger Polymer 2 apps with Redux Reselect</a></li><li><a href="https://medium.com/@jalalio/step-3-how-to-make-async-api-calls-in-a-polymer-2-app-using-redux-thunk-middleware-c71d596c2005">Step 3: How to make async API calls in a Polymer 2 app using Redux Thunk middleware</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c71d596c2005" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step 2: How to structure larger Polymer 2 apps with Redux Reselect]]></title>
            <link>https://medium.com/@jalalio/step-2-how-to-structure-larger-polymer-2-apps-with-redux-reselect-f588e64a191a?source=rss-7aed01b0bfec------2</link>
            <guid isPermaLink="false">https://medium.com/p/f588e64a191a</guid>
            <category><![CDATA[polymer]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-components]]></category>
            <dc:creator><![CDATA[Jalal Fathi]]></dc:creator>
            <pubDate>Fri, 19 Jan 2018 19:36:00 GMT</pubDate>
            <atom:updated>2018-06-15T13:21:23.666Z</atom:updated>
            <content:encoded><![CDATA[<h4>A 3-step tutorial on how to integrate Redux into a larger Polymer 2 app showcasing a working example.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*wlJVyw4w9KNcBiGJ0vzdCA.png" /></figure><p><strong>Step-2</strong> shows how to use Redux Reselect in a polymer app. If you already familiar with Redux Reselect and you want to learn more about calling API endpoints with Redux continue with <a href="https://medium.com/@jalalio/step-3-how-to-make-async-api-calls-in-a-polymer-2-app-using-redux-thunk-middleware-c71d596c2005">Step-3</a>!</p><pre>// If you want to clone this tutorial:</pre><pre>git clone <a href="https://github.com/JaySunSyn/ReduxTodo.git">https://github.com/JaySunSyn/ReduxTodo.git</a><br></pre><p>and make sure to uncomment the step-2 import in index.html</p><pre>&lt;!-- &lt;link rel=&quot;import&quot; href=&quot;/step-1/my-app.html&quot;&gt; --&gt;<br>&lt;link rel=&quot;import&quot; href=&quot;/step-2/my-app.html&quot;&gt;<br>&lt;!-- &lt;link rel=&quot;import&quot; href=&quot;/step-3/my-app.html&quot;&gt; --&gt;</pre><p>In the <a href="https://medium.com/@jalalio/step-1-how-to-use-redux-with-polymer-2-7bcfaee6fdb3">previous post</a>, we’ve put all redux logic into a singleredux-mixin.html file. ( see/step-1/ directory).</p><p>This can get quite messy because:</p><ol><li>Reducers are most likely to get blown up.</li><li>In our Polymer elements we hard code the action types and statePaths. If something changes, we need to change it everywhere.</li><li>Don’t repeat yourself. If our requirements for an object’s normalisation changes, we want to execute that change in a single place.</li></ol><p>So let’s create 3 more files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*lMD__t5bGmw6lMY5FKE5XA.png" /></figure><h3>Selectors</h3><p>redux-selectors.html</p><p>First, let’s install reselect</p><pre>npm install --save reselect</pre><p>Selectors are like computed properties in Polymer. We create them centralised in our Polymer app. They can depend on multiple arguments and get re-computed if the respective state changes.</p><blockquote>=&gt; Selectors can compute derived data, allowing Redux to store the minimal possible state.</blockquote><blockquote>=&gt; Selectors are efficient. A selector is not recomputed unless one of its arguments change.</blockquote><blockquote>=&gt; Selectors are composable. They can be used as input to other selectors.</blockquote><p>Let’s take a look at a light version of our selector code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d258380305d0986a1bf67561f9836f1f/href">https://medium.com/media/d258380305d0986a1bf67561f9836f1f/href</a></iframe><p>We have two selectors. todos which just returns the todos array of the state and todosUpper which returns an upper case version of our todos array. They get re-computed each time state.todo.todos changes.</p><p>Let’s take a look at how our &lt;todo-list&gt; element properties change when having selectors in place.</p><p>Before:</p><pre>static get properties() {<br>    return {<br>        todos: {<br>            type: Array,<br>            statePath: ‘todos’, // hard coded<br>        },</pre><pre>    };<br>}</pre><p>After:</p><pre>static get properties() {<br>    return {<br>        todos: {<br>            type: Array,<br>            statePath: App.select.todos, // cool<br>        },</pre><pre>        // let&#39;s get also the upper case version    <br>        todosUpperCase: {<br>            type: Array,<br>            statePath: App.select.todosUpper,<br>        },<br>    };<br>}</pre><p>We can now reference computed selectors in the statePath attribute of our elements - which is much cleaner.</p><h3>Actions</h3><p>redux-actions.html</p><p>In the previous post, we included respective actions into each element. Let’s add all actions to one file. At a later stage, we can include our actions getter into the ReduxMixin which will save us some writing work.</p><p>The code is quite straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e962441fc824c1ad868dd6cdd8d2ffc3/href">https://medium.com/media/e962441fc824c1ad868dd6cdd8d2ffc3/href</a></iframe><p>Because we’ll include the actions getter into the mixin, we don’t have to write the getter in each and every Polymer element.</p><h3>Reducers</h3><p>Similar as with the actions, let’s just put the reducers into a separate file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe2d781867800a78c9fc809fbe2e1bcc/href">https://medium.com/media/fe2d781867800a78c9fc809fbe2e1bcc/href</a></iframe><p>Nothing much changed here. We only make the Reducer available in the global space via App.rootReducer.</p><h3>ReduxMixin</h3><p>redux-mixin.html</p><p>The place where everything comes together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6b66956cdf32714f9b70a81eb9b6923/href">https://medium.com/media/d6b66956cdf32714f9b70a81eb9b6923/href</a></iframe><p>Please notice that App.ReduxMixin is based on ActionsMixin where we define the actions getter.</p><h3>Using it in our Polymer elements</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/279477edc4178f7550d89c505edbe0f3/href">https://medium.com/media/279477edc4178f7550d89c505edbe0f3/href</a></iframe><p>We extend our element from App.ReduxMixin to include the Redux magic. Notice that we don’t have to write an actions getter anymore. We reference the action we dispatch with App.actions.remove and pass in our todo.</p><p>Way better, right?</p><blockquote><strong>Jalal Fathi</strong> is freelance software developer and startup founder. Passionate about web technologies and in love with Polymer. <a href="https://jalal.io/">Learn more</a> about how he can help you to create your next digital product. He works wherever he wants and tries to catch a good swell wherever he can. He wrote this bio by himself while writing in third person.</blockquote><p>Next, learn how we can asynchronously call an API endpoint using a middleware.</p><p><a href="https://medium.com/@jalalio/step-3-how-to-make-async-api-calls-in-a-polymer-2-app-using-redux-thunk-middleware-c71d596c2005">Step 3: How to make async API calls in a Polymer 2 app using Redux Thunk middleware</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f588e64a191a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step 1: How to use Redux with Polymer 2]]></title>
            <link>https://medium.com/@jalalio/step-1-how-to-use-redux-with-polymer-2-7bcfaee6fdb3?source=rss-7aed01b0bfec------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bcfaee6fdb3</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[polymer]]></category>
            <dc:creator><![CDATA[Jalal Fathi]]></dc:creator>
            <pubDate>Fri, 19 Jan 2018 19:35:36 GMT</pubDate>
            <atom:updated>2018-06-15T13:22:01.098Z</atom:updated>
            <content:encoded><![CDATA[<h4>A 3-step tutorial on how to integrate Redux into a larger Polymer 2 app showcasing a working example.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*wlJVyw4w9KNcBiGJ0vzdCA.png" /></figure><p>I assume you’ve heard of Christopher Turner’s <a href="https://github.com/tur-nr/polymer-redux">tur-nr/polymer-redux</a> element. We are using his element and showcase a working todo list app.</p><p><strong>Step-1</strong> shows how to use polymer-redux. If you are already familiar with polymer-redux, continue with <a href="https://medium.com/@jalalio/step-2-how-to-structure-larger-polymer-2-apps-with-redux-reselect-f588e64a191a">Step-2</a>!</p><pre>// If you want to clone this tutorial:</pre><pre>git clone <a href="https://github.com/JaySunSyn/ReduxTodo.git">https://github.com/JaySunSyn/ReduxTodo.git</a></pre><h3>Install dependencies</h3><pre>bower i -S tur-nr/polymer-redux</pre><p>and redux itself with npm:</p><pre>npm install --save redux</pre><p>Create a folder named redux where we put in all our redux related files and create a file named redux-mixin.html.</p><p>In the current step of this tutorial, we pack everything into one file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*NiBzaUdrpOhMU4v9AEO-cg.png" /></figure><h3>Creating the Reducer</h3><blockquote>A reducer is a pure function that takes the previous state and an action and returns the next state.</blockquote><p>The most basic reducer is in the polymer-redux example which is a function taking state and action as attributes and always returns the same state.</p><pre>(state = {}, action) =&gt; state</pre><p>In our example, we want to modify the state depending on the passed in action. We then return (a copy) of the modified state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60f9fdfe476427ee9e1c8521c631a6f9/href">https://medium.com/media/60f9fdfe476427ee9e1c8521c631a6f9/href</a></iframe><p>Let’s go through the file step by step.</p><p>After importing the dependencies, we tell Redux what our <strong>initialState</strong> should look like. In our case, we predefine three todos.</p><pre>const initialState = { <br>    todos: [ <br>        {text: ‘Buy Veggies’},<br>        {text: ‘Buy Fruits’},<br>        {text: ‘Buy Pizza’},<br>    ],<br>};</pre><p>(We could also define our todos as an empty array and then load the actual todos from our server which we will discuss in step 3 of this tutorial.)</p><p>Next, we’ll define the <strong>reducer</strong> itself and return the initial state if our previous state is not defined.</p><pre>if (!state) { return initialState; }</pre><p>Now it’s time to check which <strong>action</strong> we should take to modify our state. For that, let’s switch through the action.type property.</p><pre>const todos = state.todos.slice(0);</pre><pre>switch (action.type) { <br>    case ‘ADD_TODO’: <br>        todos.push(action.todo); <br>    break;</pre><pre>    case ‘REMOVE_TODO’: <br>        todos.splice(todos.indexOf(action.todo), 1); <br>    break; <br>}</pre><p>We defined two actions. ADD_TODO adds a todo to the todos array and REMOVE_TODO removes one.</p><blockquote>In Redux, we do not modify the passed in state but rather make a copy of the state, modify that copy and return a copy of the modified state.</blockquote><pre>return Object.assign({}, state, {todos: todos});</pre><p>Now we only have to create the store as well as the mixin we will use in our Polymer elements.</p><pre>const store = Redux.createStore(reducer);<br>const ReduxMixin = PolymerRedux(store);</pre><p>We created <strong>ReduxMixin</strong> which we can use in our elements to give them redux magic.</p><p>The question you might have now is: How can we trigger the reducer to be called from our element?</p><h3>Using the ReduxMixin in our elements</h3><p>In our example, we have two elements using Redux.</p><p>&lt;todo-list&gt; and &lt;todo-input&gt;</p><p>Both of them work similarly. They only trigger different actions.</p><p>Let’s take a look at &lt;todo-list&gt;:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4771d945245bb86bba3a40bf45fdcc9a/href">https://medium.com/media/4771d945245bb86bba3a40bf45fdcc9a/href</a></iframe><p>Now let’s take a step-by-step look at the file.</p><p>The first thing we notice is that TodoList extends our previously definedReduxMixin. Doing so, TodoList obtains Redux magic.</p><pre>class TodoList extends ReduxMixin(Polymer.Element)</pre><p>The one piece of unique syntax the ReduxMixin is going to give us is an additional attribute called statePath. What statePath is doing is to tell Redux what the path of this ‘todos’ property is in this big global state object. So in our case, the path is just ‘todos’.</p><pre>static get properties() { <br>    return { <br>        todos: { <br>            type: Array, <br>            statePath: ‘todos’, <br>        }, <br>    }; <br>}</pre><p>Next thing to notice is that we added actions the same way as we added properties.</p><pre>static get actions() { <br>    return { <br>        remove: (todo) =&gt; { <br>            return { type: ‘REMOVE_TODO’, todo: todo, }; <br>        }, <br>    }; <br>}</pre><p>actions() returns an object with the remove attribute (we can call it however we want). The value is always a function which returns an object with a ‘type’ property and maybe some other properties we can reference from our reducer. In our case a ‘todo’ property.</p><p>How do we trigger the reducer function to get called?</p><pre>this.dispatch(‘remove’, todo);</pre><p>We call this.dispatch(&#39;name_of_action&#39;) to call the reducer with our action. The switch statement will be executed, etc. and the state will eventually get modified.</p><p>Yay! We did it.</p><p>Our other element TodoInput works similarly. Take a look at the <a href="https://github.com/JaySunSyn/ReduxTodo/blob/master/step-1/todo-input.html">file</a> on GitHub!</p><p>Now run polymer serve -o and notice that our todos get listed without having bound them to any other polymer property. Try to click on a todo to check if the remove action works as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*zS2J9Lh0q9LTun9oIIqT2g.png" /></figure><blockquote><strong>Jalal Fathi</strong> is freelance software developer and startup founder. Passionate about web technologies and in love with Polymer. <a href="https://jalal.io/">Learn more</a> about how he can help you to create your next digital product. He works wherever he wants and tries to catch a good swell wherever he can. He wrote this bio by himself while writing in third person.</blockquote><p>Next, see how we can structure larger Polymer apps, so it does not get messy if the app grows.</p><p><a href="https://medium.com/@jalalio/step-2-how-to-structure-larger-polymer-2-apps-with-redux-reselect-f588e64a191a">Step 2: How to structure larger Polymer 2 apps with Redux Reselect</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bcfaee6fdb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>