<?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 Vaibhav Namburi on Medium]]></title>
        <description><![CDATA[Stories by Vaibhav Namburi on Medium]]></description>
        <link>https://medium.com/@vaibhavnamburi?source=rss-56be4ac21025------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*snFzHjjCt_Vt3m8q.</url>
            <title>Stories by Vaibhav Namburi on Medium</title>
            <link>https://medium.com/@vaibhavnamburi?source=rss-56be4ac21025------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 04:00:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vaibhavnamburi/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[Database Indexing — making your database fast!]]></title>
            <link>https://medium.com/@vaibhavnamburi/database-indexing-making-your-database-fast-73b4b0615275?source=rss-56be4ac21025------2</link>
            <guid isPermaLink="false">https://medium.com/p/73b4b0615275</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vaibhav Namburi]]></dc:creator>
            <pubDate>Fri, 24 Mar 2017 14:16:38 GMT</pubDate>
            <atom:updated>2017-03-24T14:16:38.886Z</atom:updated>
            <content:encoded><![CDATA[<p>Okay so what is database indexing ? What are we trying to solve ? How does this ‘thing’ make anything fast.</p><p>Lets step back a bit. Think of a scenario : you’re in a library where none of the books are organised in alphabetical order. Yeah doesn’t sound like a pretty picture does it?Let’s try dramatise this further, where you have to find this book to win a million dollars, and you’re sure that the book is in the library.</p><p><strong>Why is it realistically needed ?</strong></p><p>If there are 5000 books in the library and it takes you 1 second to read the title of each book, we can safely assume it would need take you 5000 seconds and access to every book presuming the worst case where your book is the last book you’ll find. Now flip side, if the books were alphabetically ordered on table, (evidently the longest table to ever exist), your life would be a lot easier, at every point you’ll need access to only (number of books/2 — log2 N access — ) books. Why ? If you were looking for ‘One Minute Manager’ you would certainly know that the book would be in the latter half of the table, since ‘O’ is in the latter half of the alphabet series. This fastens up our search incredibly.</p><p>Cue music, we can think of database indexing in a similar format.</p><p><strong>Where is it needed in software ?</strong></p><p>Data is stored in disks as blocks of data. Blocks of data are self aware, similar to linked lists, they have a pointer to the location of the next block. Data blocks are stored in context to a singular field, i.e they can’t be stored based on both their ‘age’ property as well as their ‘name’ property. In a situation where the data is stored in reference to the ‘name’ attribute,but we’re trying to find a data node based on ‘age’, we’ll need access to the entire table storing all the nodes, i.e N access. And likewise in a situation we need access to information on a field with which the nodes were organised, we’ll need ‘N/2’ access (N being total blocks). In a linear search, i.e the former the resource exhaustion would be a lot more as compared to in the latter system where we can execute a binary search which has a log2 N,</p><p><strong>Now what is indexing ?</strong></p><p>Indexing is a way of sorting nodes based on multiple fields. When we create an index based on a field in a database our database system creates another ‘reference’ data structure, whose task is to hold the field value and a pointer to the original record that it is associated with, now this data structure is sorted which lets us perform a binary search on our table, which as we concluded above to be relatively more performant.</p><p><strong>Lets try get a little practical</strong></p><p>We are assuming the use of a MySQL database using MyISAM as the default storage engine, which uses a default block size of 1024 bytes or 1KB.</p><p>Suppose you have a data node, that consists of :</p><p>-name</p><p>-age</p><p>-address</p><p>-primary key</p><p>Let’s say each of these nodes have a weight of 204 B which calculatively announces that we have 5 records (Blocking factor) in a disk storage block. If our sample DB had 10,000,000 records it would be ideal to say that the total number of blocks required would be 10,000,000/5 = 2,000,000 storage blocks.</p><p>If we were to do a linear search on this assuming the value we’re searching for is not the one used to index the data nodes, then we would need access to an average of 1,000,000 blocks. However if we were searching based on the id field, i.e a field that is already sorted we would be looking at a binary search i.e log2 2000000 = 20.93 block accesses. Voila we just went from 1,000,000 block access requirements to 20 by simply working with a sorted attribute.</p><p><strong>Optimising for a non-sorted attributes</strong></p><p>What if we’re trying to effectively do a search for the address, a binary search wouldn’t work since we haven’t sorted out our database based on that, we would need to do an linear search i.e requiring access to an average of 1,000,000 records, which is no good.</p><p>Indexing in this situation makes sense, where we create a table with nodes containing just two attributes:</p><ul><li>Address</li><li>The pointer (which are 2–5 bytes in size)</li></ul><p>Assuming that the address is of type CHAR i.e size on disk is 50 bytes. We can say that each node is around 55 bytes, working off a similar procedure the blocking factor would be 1024/55 = 18.6 ~ 19 records per disk block. Using this approach the index table will consist of 10,000,000 / 19 = 526,315 records. This is sorted so we can do a binary search, doing a log2 526,315 calculation reveals we need access to 19 blocks. This again is significantly lower than the initial access to 5,000,000 for a linear search.</p><p>What we need to consider when indexing DB attributes is the speed to space expense, is the excess speed in indexing worth the cost in DB expansion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73b4b0615275" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The future of React / ReactJS — React Fiber]]></title>
            <link>https://medium.com/@vaibhavnamburi/the-future-of-react-reactjs-react-fiber-48e54f8c01fb?source=rss-56be4ac21025------2</link>
            <guid isPermaLink="false">https://medium.com/p/48e54f8c01fb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Vaibhav Namburi]]></dc:creator>
            <pubDate>Sun, 19 Feb 2017 11:44:25 GMT</pubDate>
            <atom:updated>2017-05-30T02:54:39.825Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re in involved in front end development, you’re used to the changing tides that occur ever so occasionally. If you’re involved in any development that is front end, you’re often warned to stay away, not because it’s tough but because of how exhaustive it is to learn and keep up with the frequency of all the frameworks that pop up, and become a new “fad”, dare I say ever, so often.</p><p>In the midst of all of this, there are two kings that prevail, at least in terms of downloads &amp; contributions &amp; industrial adaptation, this may fail in other contexts, these are Angular and React. We won’t go into Angular in depth, but know that Angular is Google’s brain child and was one of the reasons for changing web and introducing the Front End and Back End independence model, as to back end templating. Angular is scheduled to release V4, not 3 very soon, this skip is intentional and to do with their internal packages versioning — Angular Router was in V3 when the rest of the Ang suite was in v2, and to avoid this future confusion, Ang router will continue it’s natural increment to V4 and the rest of Angular will follow.</p><p>Sorry for that, had to give credit and context to Angular, it is an amazing tool. But to the topic of this blog — React. In relay of what was mentioned at the start, let frameworks come and go, React (and Angular) are here to stay, why, well mainly because React is great internally, not just a buzzword, it solves an actual problem, makes development componentized and sensible, its ridiculously intelligent and fast, but more importantly it’s back by one of the biggest companies in the world, Facebook.</p><p>So React moved from its 0.12,0.13 etc versions straight to 15.x.x on April 7, 2016. But what about it in 2017, is React a fad that is going to die ? I mean it has lived past the age of most frameworks, 4 whole years since its 2013 release :o. Well it’s not going, its here to stay, for a while at least-ensue the topic of discussion React Fiber, React’s future.</p><p>The project was highly experimental, and has been in the works for almost two years, but is conceptualising to something more tangible as we speak. No this doesn’t mean we have to relearn React, it’s just a complete internal re-write of React, mainly focused around updating and further optimising the famous reconciliation (diffing) algorithm, the same algorithm made famous via React’s Virtual DOM.</p><p>Why rewrite though ? It comes around the context of scheduling, in computational terms, when should a task be performed and how to prioritise tasks, in Reacts context reconciliation, re-rendering via setState/prop changes as examples.</p><p>On a side note, lets talk about two software approaches. The push and the pull approach.</p><p>In a push based approach, you as an application decide when to do a process</p><p>In a pull based approach, the library is allowed to be smart enough and make those process decisions for us. In the current version of React, the library decides when to follow through with a process.</p><p>There, however, is no scheduling involved in React, i.e if a user triggers an event that causes external library state change, you know MobX, redux, “insert buzzword”, which then causes a component to re-render, or if there is an internal re-render via the setState method, the entire component and its subjective subtree re-render synchronously, i.e priority isn’t given over another process. More context, what would you reckon be more important, a click that causes a small UI change, or an animation that is running at the same time at 60fps? In my opinion, A drop in frame-rate for animations is always destined for poor user experience as to a small delay in the change of a value due to a user interaction. Without scheduling all updates are characterised with the same priority, which can sometimes lead to poor UX.</p><p>Another cool example would be deprioritizing rendering of items in long lists that haven’t yet appeared on the the users active screen. If a component that isn’t on the screen is updated, is it even important to stop all other processes to re-render it ?</p><p>In reference to scheduling is concurrency, i.e concurrency in a single thread as to multi-thread (parallelism). A call to re-render a parent would cons-equate to that parent’s entire subtree to re-render synchronously without any interference.</p><p>How do we fix this, well common sense would suggest to interrupt low priority work, do the suddenly high priority work that just showed up, finish that — and then go back to the low priority task.</p><p>Alright — quick quiz, could you tell me what a React component is, it its raw essence, minus all the JSX and ES6 stuff ?</p><p>If you guessed, a function, you’re right. A react component is nothing but a function of data, and in that terminology, ‘rendering’ basically means calling a function. Now with that being said, how do we stop a sub-tree from re-rendering, i.e how to we interrupt a function call ?</p><p>If you guessed generators, you actually are correct, but in the implementation of React Fibre not exactly, however the concept of generators can loosely apply.</p><p>Side note again, have you ever used stashing in your git flow ? When you want to temporarily cache your disk changes , do something else, and bring those disk changes back ? i.e stashing. If you have existing changes, and you want to pull code down, you’ll most likely go through an error that’ll suggest deleting or stashing changes, if you stash, you store this changes in a stash “imaginary array”, then you complete your git pull, and then you “pop” the stash, similar to an array and your stashed changes are brought back to disk.</p><p>React Fibre does something similar, but more similar to how call stack tracing happens in Chrome’s debugger tools. In the words of Andrew Clark (Redux co-creator), React Fibre is a virtual stack frame, with React Fibre being a reimplementation of a stack frame specialised for React components. Each fibre can be thought of as a virtual stack frame where information from the frame is preserved in memory on the heap, and because info is saved on the heap, you can control and play with the data structures and process the relevant information as needed.</p><p>It is also to be noted that each stack frame has a number signifying priority relative o the other stack frames. It also contains a field that memoizes input invoking a re-render only if input has changed (kinda like shouldComponentUpdate, or when we extend to PureComponent) , and of course keys for optimal reconciliation (diffing)</p><blockquote><em>Footnote — This article has been heavily inspired and influenced by Andrew Clarks talk in 2016 on React Fibre. He joined the facebook team recently and is helping build the future of React with Dan Abramov.</em></blockquote><p><em>He continuously keeps us, the rest of the world, on React Fibre’s architecture and progression. Follow &amp; Star </em><a href="https://github.com/acdlite/react-fiber-architecture"><em>https://github.com/acdlite/react-fiber-architecture</em></a></p><p><em>PS, i know i’ve called in Fibre in the blog and not Fiber, blame autocorrect.</em></p><p><a href="http://www.five2one.com.au/"><em>www.Five2One.com.au</em></a><em> is a software consultancy based in Sydney, we’ve built products for start ups and large tech firms. We’ve worked with global startups and multi-national companies ranging from the Insurance, Aviation, Law, Car Manufacturing all the way to the Betting industry. Get in touch and lets make software development collaborative, sensible and great!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48e54f8c01fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup React Server Side Rendering …QUICK!]]></title>
            <link>https://medium.com/@vaibhavnamburi/setup-react-server-side-rendering-quick-61bb7b0927b7?source=rss-56be4ac21025------2</link>
            <guid isPermaLink="false">https://medium.com/p/61bb7b0927b7</guid>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vaibhav Namburi]]></dc:creator>
            <pubDate>Sun, 21 Aug 2016 03:36:14 GMT</pubDate>
            <atom:updated>2016-08-22T15:07:48.224Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the main advantages you get with React other than its intelligent Diffing algorithm coupled with its Virtual DOM, Component based architecture is Server Side Rendering.</p><p>When you build a react application, you create a bunch of JS files that are compiled into a bundle either by a tool such as browserify/webpack. But that’s where the issue lies, is that the server sends the client a massive javascript file that needs to be evaluated and “rendered” on the target end. So in terms of SEO, thats not the best, because when crawlers are looking to index your website for key text words, those words yet have to be rendered/evaluated.</p><p>By implementing server side rendering, you alleviate yourself from this problem all whilst enjoying react. You see traditional websites/Wordpress sites or any back end that uses a templating engine responds to a get request to their main website with HTML content. But like mentioned, with React since all your content and essentially entire website is a giant JS file, you have to wait for this code to be executed and “Rendered” when it lands on the clients browser, with SSR, you send back executed and rendered HTML.</p><p>The process generally involves fetching seed data either from a database request or from an api endpoint of your own domain, the resolved data is injected into the preloaded state and is used on initial render to the client.</p><p>Another advantage you get with SSR, is an extremely snappy website, since that initial rendering step is already taken care of so all that is left is to have this content, latch onto the client DOM or as referred to as — Mount onto the DOM. This helps us in segregating execution code, any code that may have external dependencies can be placed on a React components “componentWillMount” lifecycle function; and this will only execute on the Mount.</p><p>Alright, lets get into the setup, I’ll be using a NODE.JS backend, but assume similar principles for perhaps a PHP/any other back end.</p><p>The folder structure is as such</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*VGodV_nefEC2o0WiksrtYw.png" /></figure><p><strong>Let’s walk through this.</strong></p><ul><li>Components contains the main App React component that withholds the connected WeatherData container which is located in the containers folder</li><li>RootReducer amalgamates all the reducers that make up the global state and returns a pure object, which will be used by the <em>createStore</em> method for generating the redux store.</li><li>Since this application is routed on the front end, the routes are curated in the routes.js file</li><li>ConfigureStore.js acts as a point to create the redux store, along with hydrating this store with any initial data whilst enhancing it with middleware such as thunks or promise resolvers</li><li>Index.js acts as an entry point for the for our module bundler, this is where we render our React application to the DOM.</li><li>Server.js will host this project and contain logic for all server side rendering.</li></ul><p>Lets go through each of these:</p><p><strong>components/App.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*9ROi547j8pUbHLNUlBKUMg.png" /></figure><p>We import React and createComponent function from the React module . We render the children of this component which will be hosted in the routes folder.</p><p><strong>containers/WeatherData.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*jJEG6Ph3-jBk2wRYuztGmw.png" /></figure><p>Another straightforward file, this invokes a method on mounting, again — this would not be touching until it reaches the front end, as mounting is independent of rendering.</p><p><strong>rootReducer.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*o0p0LCNrB8Va1D20HCavsA.png" /></figure><p>A switch statement reacts to the action provided to it and returns a completely new version of the initial state with the respective changes instructed by the action.</p><p>Using the <em>combineReducers</em> function from <em>redux, </em>we pass in an switch statement function that takes in an initial state as well as an action object which mutates it. In this example, for simplicity, we’ve restricted ourselves to one state, however, in most cases there would be multiple — justifying the use of <em>combineReducers </em>(used for example purposes)</p><p><strong>routes.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*bpbt7BmPN-BsKBBT-J2ZlA.png" /></figure><p>Using the IndexRoute we map — WeatherApp as a child of the App component</p><p><strong>ConfigureStore.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*SGysqPmGQB_P64PMDLi7Wg.png" /></figure><p>The file default exports a function which is invoked by an argument that acts as an initial state to the application. We will late go on to understand that this initialState was send from the back end.</p><p>We pull in two functions from the ‘redux’ module:</p><p><em>createStore, applyMiddleware</em></p><p><a href="https://github.com/reactjs/redux/blob/master/src/applyMiddleware.js"><em>applyMiddleware</em></a><em> </em>takes in the imported/custom middleware.</p><p><a href="https://github.com/reactjs/redux/blob/master/src/createStore.js"><em>createStore</em></a>, which takes as its arguments, the rootReducer (which we’ll look into very soon), an initial hydrating state and an enhancer-which in this case is the applyMiddleware function. You note the existence of the compose function, without going into too much detail, the purpose of this is to rightReduce all the middlewares that would be provided.</p><p>Read into <a href="https://medium.com/@vaibhavnamburi/trying-to-understand-redux-and-redux-middleware-5f52fd5ef354#.t0rg6ogtc">this</a> post to better understand the redux architecture.</p><p>Another configuration you can also look into is below, the flexibility arises from the architecture that is Redux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCsc4J8UwYIIwqZdaAgfug.png" /></figure><p>The differentiating factor being, when using createStore with middleware, the second argument is the preloaded state, in a situation your server is not optimised to load any initial data, you are forced to leave that argument undefined. Although there might be a situation where on mounting a component you want to go ahead and fetch data from an API and load that into the store, sortof similar to initial state load, in such a situation using the configuration above helps, as <a href="https://github.com/reactjs/redux/blob/master/src/applyMiddleware.js">applyMiddleware</a> itself returns a function that would be invoked with the createStore function which then would be invoked by its three respective arguments, the reducers — initial state — and additional enhancers.</p><p><strong>Index.js</strong></p><p>This is the main entry point file, as stated, in the client side of the application. There will be some code repetition between this file and the server.js file which is completely intentional. This is what will help with the speed, when the client receives any new data, instead of re-rendering it will use the rendered HTML for differentiating and injecting only the necessary changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*BgsY2SIMNeJkg4dSFjYLiw.png" /></figure><p>This will look similar to most stock react app configurations, the difference appearing in line 10, this will make more sense once we jump into the server file, however to get your feet wet, essentially — we load in the initial state from the server generated HTML stored as global window variable under the __PRELOADED_STATE__ attribute . When this is received on the client end, we inject into our store as the initial state (hydration), which the client side will use on initiation.</p><p><strong>Server.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*ZWcs2vOZI37Od3sm_ldTyg.png" /></figure><p>Alright there’s a few things happening here — lets go through them line by line.</p><p>We invoke the express module and work of this instantiation.</p><p>The purpose of the <em>renderFullHTMLPage function, </em>is to inject our initial HTML component along with the preloaded state into a template that would be rendered on the client side. To send the state, we add a script tag that will attach this preloaded state to the global window object under the __PRELOADED_STATE__ attribute. The bundle.js file will contain the bundled outcome of your bundler and will contain the entire application.</p><p>We <a href="https://facebook.github.io/react/tips/dangerously-set-inner-html.html">dangerouslySetTheInnerHTML</a> as a method of sanitizing data and preventing XSS attacks as we’re injecting data to HTML. Read into this to understand the utility of __html.</p><p>Moving on, line 29 helps initiate our initial store using the <em>configureStore</em> method we created earlier.</p><p>Using the renderToString method extracted from ‘react-dom/server’ we create a stringified version of the client side application instantiation. We still need to pass the initial state to the <em>renderFullHTMLPage </em>function; since configureStore returns the redux store, along with helper methods — we use them to get access to the pure state-done on line 37.</p><p>And with that simple configuration, you now have client side rendering of your react application.</p><p>If you look into the github project you’ll see in the server file, that i’ve requested for data from an API endpoint, I await for it to resolve and pass this data i receive to the initialStore. This is then picked up on the front end via a console.log, whose output you can see in you log.</p><p>Note: if you want to use this to test, make sure you register for an API from openweather.org and place it in on line 18.</p><p><a href="https://github.com/veebuv/react-redux-server-side-rendering-boilerplate">https://github.com/veebuv/react-redux-server-side-rendering-boilerplate</a></p><p>Hope this helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61bb7b0927b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Actions creating actions, ACTION CREATORS!]]></title>
            <link>https://medium.com/@vaibhavnamburi/actions-creating-actions-action-creators-eea7017011b5?source=rss-56be4ac21025------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea7017011b5</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Vaibhav Namburi]]></dc:creator>
            <pubDate>Sat, 28 May 2016 02:15:39 GMT</pubDate>
            <atom:updated>2016-05-28T02:15:39.933Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever come across a situation where you want a button click to not just dispatch one action but perhaps dispatch three ?</p><p>A situation that would fit really well for this in UI/UX would be, to update the status through the redux state when an action was successfully dispatched, when the data was received by the back and finally when the back end responds with an outcome.</p><p>It’s simple to do this, but just like any other post — we’ll need to understand the ecosystem the functions thrive under to figure out why their architecture is designed as such.</p><p>Here’s the example we’ll walk over :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*MpBaHS_MJFSd6JSTWb8DUg.png" /></figure><h4>Firstly, have you heard of a thunk?</h4><p>I like to think of a thunk as a sub-routine made generally to call another sub-routine. A sub-routine can be thought of as a series of instructions needed to be executed to conclude with a particular result.</p><p>So where does thunk fall into all this? Well like we described above, we essentially are creating a delayed action for response. We create a function, that then invokes other functions (or instructions) when required rather immediately.</p><p>Back to the example:</p><p>It seems noisy, but I’ve just named the actions descriptively. The main action creator returns an anonymous function that’s invoked with the Redux store’s dispatch and getState functions, using the latter we check for the current request status, based on this we dispatch respective actions which updates the UI/UX accordingly. This follows on for different stages in the request, i.e:</p><ul><li>ending the current session</li><li>waiting for the promise to resolve</li><li>catching errors, if any</li></ul><p>Pretty straightforward, so to speak. But I still haven’t addressed the structure of this action creator. Why do we wrap all these individual actions in an anonymous function ? We do this so that it’s intercepted by the redux-thunk middleware — I won’t go into detail on this, but feel free to look into my middleware’s blogpost. Below is the structure for the redux-thunk middleware:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*K1r2RXs2zl1et0WdewM3aQ.png" /></figure><p>As you can see, the action on <em>line 4 </em>is invoked with the store dispatch and getState functions — hence allowing us access to them in the anonymous function we return from an action creator.</p><p>That’s pretty much it folks!</p><p>All the best!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea7017011b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trying to understand Redux and Redux Middleware]]></title>
            <link>https://medium.com/@vaibhavnamburi/trying-to-understand-redux-and-redux-middleware-5f52fd5ef354?source=rss-56be4ac21025------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f52fd5ef354</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Vaibhav Namburi]]></dc:creator>
            <pubDate>Mon, 23 May 2016 14:05:19 GMT</pubDate>
            <atom:updated>2016-05-23T14:05:19.091Z</atom:updated>
            <content:encoded><![CDATA[<h4>What exactly is Middleware and why do you need it?</h4><h4>The Build up.</h4><p>I’ve asked this question only once, because — the second you figure out why, you’ll realise how prettyful they are. Also, i’m going to assume you are aware of React and Redux and the entire ecosystem to some extent. However, i’ll try go through concepts as they come along, including JS concepts where needed :)</p><p>For those alien to Node or any language not familiar with this concept, Middleware’s are functions that you repeatedly execute between two events, that may be between receiving a request and executing a response (in the backend), similarly we take this concept and place it with the Redux data flow cycle.</p><p>When did I realise I needed Redux Middlewares? Well I wanted to make a promise based request from my actions to the back end to receive some data. I then wanted to take this data and save it into my global store via a reducer, however — when this request reached my reducer, it was still in a pending promise state, thus my component that depended on this data couldn’t render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*uJuUqAca0AasEiyjLXxPTA.png" /></figure><p>So over here, i’m making a request to a URL I defined somewhere in the file, and this request is invoked when my component that is meant to host the list of banks is meant to be loaded.</p><h4>The use of React Component LifeCycle Methods</h4><p>This invocation is done using handy React Component LifeCycle methods. These methods are extremely valuable, the TL;DR is that — based on the stage of the component’s life, i.e is it just about to be rendered onto the page, is it going to receive new props? or is it just about to be demounted from the page?, functions can be executed. Have a read here:</p><p><a href="https://facebook.github.io/react/docs/component-specs.html#lifecycle-methods">Component Specs and Lifecycle | React</a></p><p>Based on this simple request, the reducer reciprocates with simplicity as well.</p><h3><em>What is a reducer exactly?</em></h3><p>Reducer is a function that takes the existing redux state, a mutating effect(action) and returns an updated version of the state to be fed into the global store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*zuDoHXvBkyd25ob2o_NzAg.png" /></figure><p>Using ES7 spread operators, we de-construct the existing array and add onto the object the mutating data. <strong><em>However </em></strong>disaster will strike here, as the action’s payload which was a promise would have not resolved as of yet. One way of handling this would be to resolve it within the reducer case and pass the resolved state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJaH5P52qeFfGeE3wy0_5w.png" /></figure><p>As you can see, resolving the payload, attaching it to a variable and then using that to update the state attribute is a lot of work, and this process may need to be repeated for every single request to the back end. To stick with DRY programming principles we then implement Middleware, which will conveniently fit between actions and reducers.</p><h3><strong><em>How I understand redux:</em></strong></h3><p>I use this analogy for understanding redux:</p><ul><li>Think of your redux store as a building</li><li>Each reducer as a floor manager responsible for the state of a floor (each key in the global redux state) containing many offices</li><li>Actions can be thought as construction or delivery people each of who’s goal is to change (mutate) each floor’s plan</li></ul><h4>What’s the process ?</h4><ul><li>Actions are <strong><em>dispatched </em></strong>from a React component. <br>— Actions can be thought as workers who carry two things :<br> an access key to only one particular floor and “mock furniture” to take upstairs.</li><li>The worker is not aware of where he has to deliver so they visit each office on each floor trying to gain entry.</li><li>When their access key matches, they place the fix the furniture, and ring their manager<br> — the manager creates an exact copy of the floor offsite and replaces that entire floor in the building with the new changes in place.</li><li>Middlewares act as the pedantic security guards next to the lifts.</li><li>Taking the example of Redux-Promise:<br>It checks if anyone entering the lift is bringing in unassembled “ furniture”, <strong><em>work in the state of pending (promises),</em></strong> and if so, they make you wait till you assemble it and grant permission.</li></ul><h4>Converting this analogy into the actual flow.</h4><p>Taking the example of a component needing data from a server to load onto a list :</p><ul><li>On component mounting, an action is dispatched which sends an axios request to the back end, the retrieved data is contained within the payload attribute of the action</li><li>Just before reacting the reducer, the action passes through the redux-promise middleware we will install, this will resolve the promise and send the resolved data to the reducer</li><li>The action passes through all the reducers and when it fits the right action type, the payload of the action is used to return a completely new version of the previous state with the new data in place</li><li>This causes a redux flush, i.e all the React components connected to the redux store, depending on the global state properties that just changed will be re-rendered and flushed with the new data. This is immediately reflected and showcased.</li></ul><p>With that being said, back to Middlewares and how they actually work. Middlewares have a rather noisy structure, but if we go in and understand the reason behind all of the extra lines of code and <em>complexity</em> it’ll make sense. Especially so when we go into understanding on a broader scale how some of redux’s helper functions work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KFmpCIzTLr1h35ncYNB6g.png" /></figure><p>This is my index.js file, i.e the entry point for my module bundler (webpack). Lets go through it:</p><ul><li>Theres a bunch of core imports, middleware and the App component along with the combinedReducers result</li><li>We then use the applyMiddleware function shipped with redux and invoke it with all the middlewares (we’ll be visiting this soon), the returned function is then invoked with the createStore function: <a href="http://redux.js.org/docs/api/createStore.html">http://redux.js.org/docs/api/createStore.html</a></li><li>To the ReactDOM.render function we pass in a provider instance with a store prop which will create a store using the reducers while keeping in mind the purpose of the middleware</li><li>The provider acts as a convenience factor by making the global redux store available to every <em>connected </em>component rather than individually passing it on each time. Have a read at the docs if you wish, but thats pretty much it : <a href="https://github.com/reactjs/react-redux/blob/master/docs/api.md#provider-store">https://github.com/reactjs/react-redux/blob/master/docs/api.md#provider-store</a></li><li>This is rendered onto the HTML using a div with the class target : container</li></ul><p>All this talk and still no middlewares, patience is virtue my friend.</p><h4>Middlewares’ structure as on now</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*W6Zt5sw_YjuRx58h1EzhwA.png" /></figure><p>This uses ES6 syntax and looks way confusing. Lets go ahead and make this ES5, with a little less noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*d4B0Yu0BfHMJlyCILFH_Ew.png" /><figcaption>Structure of a middleware logger function</figcaption></figure><p>Okay, so not exactly perfect, but at least it’s a little more verbose.Lets walk through it.</p><p>P.S this is pretty much a currying function,</p><h4>What is Currying?</h4><p>Without going into too much depth, think of currying as a convenience being used when you don’t want a function to contain many arguments, instead you use one of JavaScript’s specialities to perform currying.</p><p>Currying helps with :</p><ul><li>Higher order functionalities</li><li>Memoization</li><li>Avoiding passing the same arguments again and again.</li></ul><p>From the above structure it’s safe to assume that the function needs to be invoked thrice.</p><h4>ApplyMiddeware architecture</h4><p>Moving on we really need to dive into how <strong><em>applyMiddleware </em></strong>really works to wrap our heads around this. The link to the code is :</p><p><a href="https://github.com/reactjs/redux/blob/master/src/applyMiddleware.js">reactjs/redux</a></p><p>Here’s the image of it, it you’re too lazy to click on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mU5F5IBTNK8tGaTVUTJAQA.png" /><figcaption>Apply Middleware function</figcaption></figure><p>Seems like a mouthful, but I promise you its not bad. Alright, line by line.</p><pre>export default function applyMiddleware(…middlewares) {</pre><p>This is just the function declaration, the *…* in front of the argument is ES7&#39;s spread operator, I encourage you to look into it.</p><pre>return (createStore) =&gt; (reducer, initialState, enhancer) =&gt; {</pre><p>applyMiddleware returns a function, which is invoked with the createStore :</p><p><a href="http://redux.js.org/docs/api/createStore.html">Redux</a></p><pre>var dispatch = store.dispatch</pre><p>It assigns the Redux store’s dispatch function to a locally defined variable</p><pre>var chain = []</pre><p>Predefine a array to which we will map data</p><pre>var middlewareAPI = {<br> getState: store.getState,<br> dispatch: (action) =&gt; dispatch(action)<br> }</pre><p>We define an object setting the getState attribute from the store itself and the dispatch attribute from the local dispatch we defined.</p><pre>chain = middlewares.map(middleware =&gt; middleware(middlewareAPI))</pre><h4><em>Array.prototype.map : How does it work?</em></h4><p>It loops through the middlewares’ argument invoking each middleware with the middlewareAPI object. This is our first middleware invocation, i.e this is passed in as the <strong><em>store </em></strong>in the main middleware function, i.e <em>line 1</em> in the picture of the middleware logger function</p><pre>dispatch = compose(…chain)(store.dispatch)</pre><h4>Redux’s Compose function</h4><p>Compose is a function shipped with Redux and it rightReduce’s all the middleware functions, invoking the last middleware with the Redux store’s dispatch function. So if we had a series of middleware in the chain such as</p><p><em>[y,b,x,d]</em></p><p>after the compose function we are returned :</p><p><em>(…args) =&gt; y(b(x(d(…args))))</em></p><p><strong>credits to Dan Abramov on being a genius</strong></p><p>More on that in the link below :</p><p><a href="https://github.com/reactjs/redux/blob/master/src/compose.js">reactjs/redux</a></p><h4><strong><em>How does reduce work?:</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*Pi74CEF_1T7J210-jioCwA.png" /></figure><p>_.each works exactly like the native each, except it takes the collection as an argument rather as a prototypal method. Following the native reduce architecture:</p><ul><li>it takes an iterator and an accumulator as arguments.</li><li>If we don’t provide an accumulator, the function sets the first element in the collection as the accumulating value.</li><li>Iterating function’s first argument is the accumulating value, the second is the element in the collection</li><li>The accumulator is updated with the returned value of the iterator which is returned at the end of the each loop</li></ul><p>So when the compose function is executed, it would have returned a function that would be then invoked with <strong><em>store.dispatch </em></strong>as seen on <em>line 12 of the ApplyMiddleware function</em>. The important part to understand is, the <strong><em>same </em></strong>dispatch function is used through all the middlewares to keep a unison in the result being achieved. All this returns what becomes the dispatch function for the store.</p><p>It is hosted within an anonymous function that is returned and invoked with the <em>createStore </em>function which takes in the combinedReducers as it’s initial argument, as seen and explained on <em>line 2.</em></p><p>Wow that was a lot, it took me a while as well, so read over it as many times as you want and most importantly refer to the actual code with the links provided.</p><p>With this set in mind, lets write down, how we’ll approach creating our own redux-promise middleware.</p><h4>Re-writing a basic Redux-Promise by ourselves</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*6FTaWPZ7t6Ew8aVCK43pMQ.png" /></figure><p>To check if an action’s payload contains a promise, we tap into the <strong><em>then </em></strong>function native to a Promise object. If this doesn’t exist, i.e it’s not a promise, then we go ahead and dispatch it like any other action.</p><p>If it does consist of a <strong><em>then </em></strong>function, all we do is, resolve the Promise, update the present action’s payload with the resolved data and then interestingly invoke the store’s dispatch with this ResolvedAction.</p><p>The reason for this is straightforward; the order of middleware’s are not curated, nor are they meant to be. Some middlewares may require an action not to be a promise but don’t necessarily check for it. So for the sake of these, we do a <em>master </em>dispatch, so that the <strong><em>now resolved version </em></strong>of the action enters the middleware chain again, this time round however it dispatches normally since the action no long contains a promise.</p><p>That’s pretty much it folks, I know — it can be really intimidating and overwhelming for some, but trust me, just read though this again and again along with the actual redux docs (which are honestly fantastic) and it’ll eventually make sense.</p><p>All the best!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f52fd5ef354" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My $200 alternate guideline if you can’t afford a $11000 Junior Programming bootcamp!]]></title>
            <link>https://medium.com/@vaibhavnamburi/my-200-alternate-guideline-to-a-11000-junior-programming-bootcamp-a1e3e63891b1?source=rss-56be4ac21025------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1e3e63891b1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bootcamp]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vaibhav Namburi]]></dc:creator>
            <pubDate>Thu, 12 May 2016 06:59:10 GMT</pubDate>
            <atom:updated>2016-08-07T02:11:11.284Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re reading this, you’re keen to pick up software — either for fun or to make a career switch. Being someone who’s done this and failed enough to learn the right path, I can try point you guys in the right way.</p><p>Firstly you want to start of easy, if you inundate yourself with heaps of technical things (believe me, there is just WAY too much to learn in one life time) you’ll eventually burn out and the fire inside you will die. The key to success in software or anything is incremental progressive growth - keep the mind fresh while continuously encouraging exploration through living on the edge.</p><p>In this post i’ll try explain some of the bleugh technical words that keep popping up.</p><p>Alright, so you want to learn JavaScript ;) Honestly, there’s no reason to learn anything else if you’re beginning software with an intension to get into web or app development. Now understand that this is development, if you want to grow into an engineer there are a fair few extra milestones you’ll need to cover — things to do with architecture, scalability, time-space complexity to just begin with.</p><p>Why JavaScript? Recent survey from one of the most popular software websites called stackoverflow.com (AKA the ultimate cheat sheet for software people — i discourage going to the website unless you really really have to, try your mind’s best before you go “copy”) showed that JavaScript is the most popular language on both the front-end and back-end (ugly jargon-will explain,promise)</p><p>Also, JS is a relatively easier language to learn compared to most object oriented languages or “classical inheritance languages”. More importantly there are millions of Java Engineers with ridiculous amounts of experience, but because JS is such a versatile environment with new frameworks(uuugghhh more jargon) coming in every few months it gives an opportunity for newbies to take on the big guys and score a job.</p><p>Saved the best for last, with JS you just need to know JS!!! just with that language, you can make a web,desktop AND a mobile application — SO MUCH POWER!</p><p>So i’ve been talking all this time, let me get you guys started on.</p><ul><li>You want to know what the hell JavaScript or programming even is, so to that i suggest you go to codecademy.com and complete their JS course.</li><li>At this point you know a little about JavaScript but you really want to get into it. You want to and need to understand how the language works as a whole so you can create your own frameworks or mutate existing practices. For that you should go ahead and read ALL 6 “You Don’t Know JS” books <a href="https://github.com/getify/You-Dont-Know-JS">https://github.com/getify/You-Dont-Know-JS</a></li><li>At this point hopefully you have a much better understanding of JS as a language, and know what i’m on about when I say closures, currying or prototypal inheritance</li></ul><p>Next is the BIG PART. UDEMY!!!! I canNOT stress how amazing of a tool this platform is and even though some of the people aren’t great, there are a few who are FANTASTIC! Alright lets begin with this :</p><ul><li>Start with Anthony Alecia’s JavaScript: Understanding The Weird Parts <a href="https://www.udemy.com/understand-javascript/learn/v4/">https://www.udemy.com/understand-javascript/learn/v4/</a> . This guy goes fairly in-depth into the language, however most of the things would be familiar to you by now, since you read the books. Regardless he has a fantastic way of explaining how the language works internally and has a great command of JavaScript</li><li>Complement this with Anthony Alecia’s NodeJS Course. Node is a back end framework (a framework uses a language as a tool to create a structure, and we then use this structure to achieve results faster), so Node can be thought of as the brains that holds the actual application somewhere in the air and commands the database and stuff (very basic intro, i’ll let Anthony do the bulk lifting). This introduces you to Node JS and goes obsessively in-depth into how Node work and what exactly Node is and why it’s important. The course is not exactly complete, in the sense that you actually learn alot but apply little</li><li>Next course you should do is The Complete Node JS Developer Course <a href="https://www.udemy.com/the-complete-node-js-developer-course/learn/v4/">https://www.udemy.com/the-complete-node-js-developer-course/learn/v4/</a> — Yes a certain amount of it is repeated from the Anthony Alecia course but all the explanations are done on a practical basis and you end up build a few cool applications on the way. And like in all things in engineering, theory is fantastic and absolutely necessary but you learn the most by jumping in and making stuff</li><li>And ofcourse myself, I’ll be releasing an all intensive know it all javascript and react course, walking people through my learnings and findings. On many occasions i’ve found students to be the best teachers and hopefully I can reciprocate.</li></ul><p>Now that you did the whole back end thing, we need to work with introducing ourself to the front end, what is that you may ask, well the front end is exactly what you’re looking at right now — it is what the world interacts with. It is ALOT more than just HTML and CSS (refer next paragraph) but nowadays is heavily framework dependant as well.The reason being is that computers and mobiles have become very performant nowadays and it’s only sensible to make use of this extra power to do some of the heavy lifting locally rather have the processes be executed on some computer somewhere on the internet (the server) which costs money.</p><p>HTML and CSS are the basics of all WEBPAGES. No they are not programming languages but rather a structure to follow. HTML stands for Hypertext Markup Language, fancy words for — hey these are a bunch of tags that act as identifiers to seperate the entire web page to different sections, and CSS (cascading style sheet) is how you style/prettify a page. I encourage you guys to do the HTML and CSS sections of <a href="https://www.freecodecamp.com/signin">https://www.freecodecamp.com/signin</a> — this is a great place and if you can, go ahead and finish the entire thing and start making ACTUAL websites!</p><ul><li>Alright back to the last two. Right now, as of May 2016, ReactJS (a framework made for the front end by Facebook) is the most popular thing on the market. To get up to a certain pace with this, start off with Stephen Grider’s Modern React with Redux <a href="https://www.udemy.com/react-redux/learn/v4/">https://www.udemy.com/react-redux/learn/v4/</a> This will very slowly but fantastically welcome you to react, explain what the hell it is, why its important and also why the hell its so damn awesome!</li><li>Next, complement this with Stephen Grider’s Advanced React and Redux <a href="https://www.udemy.com/react-redux-tutorial/learn/v4/overview">https://www.udemy.com/react-redux-tutorial/learn/v4/overview</a> — here he goes into concepts of authentication and a lot of the things core to React itself and explains some cool concepts behind Testing (again i’ll let him explain this)</li></ul><p>The advantage with React is that you can use a rendition of the framework called React Native to make mobile applications. Another course by Stephen Grider himself <a href="https://www.udemy.com/reactnative/learn/v4/">https://www.udemy.com/reactnative/learn/v4/</a> . Why this framework over Java or Swift/Objective-C ?; well I sort of just answered it. You don’t need to learn two different things but use the same environment to make applications for the two most popular mobile environments.</p><p>For now, thats it folks! If you’ve done all of the above, honestly you’re probably ahead of most people, and more over you’re ahead of where you were when you began, and would be $11000 up with a chance to actually get a job too.</p><p>Here’s the disclaimer, why do I say this is an alternative? Even after bootcamps; you don’t get a job based on their reputation, you get a job based on what you execute and make.</p><p>The whole point is to MAKE PROJECTS, I CANNOT STRESS ON THIS ENOUGH. Make projects,projects and more projects. Chat applications, a new framework, a new Facebook, a robot, an artificial intelligence engine, whatever inspires you. Remember, software is one of the only environments where a significant population of the work force actually don’t have degrees but just know how to execute and contain a ridiculous amount of drive. When you sit down for a job interview, they don’t care as much pertaining to where you came from but rather what you did. Buff up your resume with projects and more projects and use that as leverage. The above steps should definitely help you to get there, and give you the confidence to make applications and place the code on GitHub (this online environment where you can share code publicly).</p><p>All being said,there are some things you can’t replace, which is human interaction and having that collaborative environment, but thats why meet-ups and after work events exist. This is an alternative to a Junior Bootcamp for those who can’t afford or just don’t have the time for one, and most of what i’ve shown is developer based, you’d like to get into the Comp Sci basis of it soon. If you have the passion, the ridiculous drive and the motivation to take on it, I would suggest this, your street cred is higher when you do things yourself rather in an environment — but that’s just me. If you’re struggling through this and feel like self study isn’t you — by all means do the bootcamp, however the resources I pointed out to are fantastic and I would recommend you do them regardless of what route you take.</p><p>Hope this helps, please ask away if you have any questions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1e3e63891b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is an event emitter and a listener ?!]]></title>
            <link>https://medium.com/@vaibhavnamburi/what-is-an-event-emitter-and-a-listener-e8b44f5bbf1b?source=rss-56be4ac21025------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8b44f5bbf1b</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vaibhav Namburi]]></dc:creator>
            <pubDate>Thu, 21 Apr 2016 16:32:53 GMT</pubDate>
            <atom:updated>2016-04-21T16:32:53.098Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever done any kind of front end, back end or any web work — you’ve come across events. Events aren’t all that magical as they’re made to seem, but yeah their concept is ace!</p><p>I first came across events when I worked with building a chat app (as every aspiring engineer does) — REAL TIME is the best. I was really interested by the concept. You know -&gt; Shoot something out into the wilderness and something out there has its ears open listening for orders to do a certain action — SO COOL.</p><p>Anyway , enough back story , eventing is really simple, like all programming of course , its just made to look like its magic.</p><p>A pre TL;DR ? Object containing an array of functions attached to a key <em>event</em> all of which are ready to be invoked with parameters being sent from the <em>emitter.</em></p><p>Thats pretty much it :D -&gt; Lets make our own eventing system.</p><p>Assume an Eventing object is similar to any Prototypal or Classical Object system, i.e we can make instances of it.</p><pre>function EventObject(eventName){<br>   this.name = eventName;<br>   this.events = {};<br>}</pre><p>This event “class” has three attributes, the name itself and all the events it’ll be hosting (more on this very soon).</p><h4>What does an EventObject.on even mean?</h4><p>It means, “hey listen, just listen out for this package that’s going to come our way, it’ll have a label `(insert-event-name)`”.</p><p>Who are we telling to listen to ? Well the object itself.</p><h4>Now what does an EventObject.emit even mean?</h4><p>Exactly vice versa, “Hey object, please send this package with a certain label name containing some specific data, it’ll be collected by the respective people waiting for it”</p><h4>Enter analogy:</h4><p>Think of the event emitters as the fancy people who land at airports and chauffeurs waiting for them with their name out and event listeners. I.E Business person has package and comes with name, driver waits for that person, and on receiving collects them and does as instructed.</p><p>Lets break it down, what does EventEmitter.on do -&gt; it creates a listener with a callback, so it’s safe to say, in the events attribute of our constructor we end up with key value pairs, keys being the event name itself and value being an array of callbacks subscribed to this event.</p><p>EventEmitter.emit looks for this particular event in the events attribute of the Object instance and runs a for loop through every saved callback, invoking each one with the data passed in with the emit.</p><p>Confused? hopefully not — lets see the basic architecture behind this</p><pre>EventObject.prototype.on = function(event,callback){<br>  if(Array.isArray(this.events[event])){<br>   this.events[event].push(callback);<br>  }<br>  else{<br>   this.events[event] = [callback];<br>  } <br>};</pre><pre>EventObject.prototype.emit = function(event,data){<br>   this.events[event].forEach(function(eachCallback){<br>   eachCallback(data); <br>   })<br>};</pre><p>The on prototypal method, takes the event name as the first argument and the callback we wish to be invoked when this event is emitted. The first <em>if</em> block checks to see if this event already exists and is an array. If so, we go ahead and add a callback to the array stack.</p><p>In the situation that it isn’t we simply create the key and add an array value containing the callback as the first index value.</p><p>—</p><p>The emit method, takes in the event as the first argument and the data as the second. We go ahead and find this event in our internal events object and run a simple forEach (for) loop through all the callbacks, invoking each of them with the data that was passed. I.E we invoke all the “subscribed” callbacks.</p><p>And that’s pretty much it ! However, it feels a little volatile, lets try add some filters for edge cases.</p><pre>function EventObject(eventName){<br>  this.name = eventName;<br>  this.buffer = {};<br>  this.events = {};<br>}</pre><pre>EventObject.prototype.on = function(event,callback){<br>  var bufferEvent = this.buffer[event];<br>  if(bufferEvent){<br>   bufferEvent.forEach(function(data){<br>    callback(data);<br>   });<br>   delete this.buffer[event];<br>  }<br>  else if(Array.isArray(this.events[event])){<br>   this.events[event].push(callback);<br>  }<br>  else{<br>   this.events[event] = [callback];<br>  } <br>};</pre><pre>EventObject.prototype.emit = function(event,data){<br>  if(!this.events[event]){<br>   var bufferedEvent = this.buffer[event];<br>   this.buffer[event] = bufferedEvent ? bufferedEvent.concat([data]) : [data];<br>  }<br>  else{<br>   this[event].forEach(function(eachCallback){<br>    eachCallback(data); <br>   })<br>  }<br>};</pre><p>Alright, so consider a scenario where you’re developing, and you know you want to emit an event, you haven’t set up a listener yet — but you will at a later stage in the development cycle. For this I introduced a buffer object.</p><p>Let’s walk through this:</p><ol><li>Event is emitted, but system realises there is no event as such in the object instance</li><li>It creates this event in the buffer as a key value pair with the data sent in — it first checks if this event exists in the buffer using a simple terinary operator</li><li>Some later stage, we listen for this event, the first thing we do is check if there are any buffered emits waiting to invoke the subscribed callbacks,</li><li>If there are — we go ahead and invoke them with the respective callback.</li></ol><p>With the little added versatility, we created very basic eventing system — conceptually at least.</p><p>Hope this helped!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8b44f5bbf1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS Higher Order Components ? YES!]]></title>
            <link>https://medium.com/@vaibhavnamburi/reactjs-higher-order-components-yes-ef98dc2acd6b?source=rss-56be4ac21025------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef98dc2acd6b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Vaibhav Namburi]]></dc:creator>
            <pubDate>Tue, 12 Apr 2016 02:00:53 GMT</pubDate>
            <atom:updated>2016-04-13T23:54:06.768Z</atom:updated>
            <content:encoded><![CDATA[<p>So mixins are old news now, Higher Order Components or “HOCs” are the new approach brilliant engineers are integrating into their ReactJS applications. So what exactly are HOCs and when will you use them ?</p><p>Simple explanation : A HOC is a wrapper component that provides a “Composed” Component (Fancy words for “baby” component) extra functionalities.</p><p>These additional “functionalities” can be simple helper functions that you want to avoid continuously importing each and every single time or more importantly, they can act as filter or an extra layer on top of your Composed Component.</p><p>Situations where I’ve used HOCs in production code :</p><ul><li>Authenticated/Protected Routing</li><li>Data parsing</li><li>Selective rendering</li><li>Anywhere you initially would want mixins</li></ul><p>These are some of the many ways HOCs can be used.</p><h4>Why did I use a HOC?</h4><p>I came from an Angular background, where I would use a pre-state change check to see if the current session is still valid, and accordingly I would control their page navigation.</p><p>I wanted to do something very similar to Angular, however, since React isn’t an MV* you miss out on some of the Angular structure, but it’s well compensated with all these additional and malleable features you can use to mirror a similar restricted concept.</p><p>Alright enough back story, lets get into the code :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8545c4e2197e7981d232e2b56f99a78/href">https://medium.com/media/f8545c4e2197e7981d232e2b56f99a78/href</a></iframe><ul><li>We import React and Component attribute (using destructured assignment) from the react module.</li><li>This follows a function creation that takes in a single argument - the “baby” component which we want to provide additional functionalities</li><li>Within the function we create a <em>Wrapper Class </em>through which we <em>inject </em>the additional <em>checks</em> we want to perform for authentication</li><li>This acts like any other React Class, and consists of a render method, here’s the fun part — we return an instance of the <em>ComposedClass </em>which we pass in as a function argument to the wrapper function</li></ul><pre>&lt;ComposedComponent {...this.props} /&gt;</pre><p>When you wrap a component, you don’t want to handicap it from receiving any props that you might provide to any of it’s instances.</p><h4>What do I mean?</h4><p>Well, what is exposed to the JS engine, is the wrapper class , so you may do something like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5100ecea6096179bc80b204f6dff25f3/href">https://medium.com/media/5100ecea6096179bc80b204f6dff25f3/href</a></iframe><p>In the above gist, we invoke the <em>isAuthenticated </em>function to return a class which acts as a wrapper class for our <em>Composed Component</em>.</p><p>So technically, what is instantiated like I mentioned is the wrapper class. The only way to pass props to the <em>Composed Component </em>is via the wrapper class, which we do so above. We are passing in a <em>prop “name” </em>with the value of “Vaibhav”</p><p>This prop is present in the wrapper, however, to make it accessible to the <em>Composed Component </em>we use the</p><pre>{...this.props}</pre><p>This gives accessibility to all the props the wrapper would have received, the <em>Composed Component </em>can simply refer to this value normally, by doing something like</p><pre>&lt;div&gt;{this.props.name}&lt;/div&gt;</pre><p>within the <em>Composed Component.</em></p><p>All we’ve done thus far is just add extra complexity, where does authentication come in this ?</p><p>It comes in at the router module -&gt; I’m going to assume you know how react router works and its’s exact usage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d426629fae92898c8e85a3334fa70fc1/href">https://medium.com/media/d426629fae92898c8e85a3334fa70fc1/href</a></iframe><p>Lets note that the application is also rigged with redux as you’ve seen above, and redux controls the user authentication state. For simplicity’s sake we assume that some one enters their credentials, this sends an action to the back end, authenticates the credentials and updates the application login state with a boolean true.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66cb4a8580433640fa64957fb7230a40/href">https://medium.com/media/66cb4a8580433640fa64957fb7230a40/href</a></iframe><p>Now…hopefully you’re familiar with the redux library, if not…don’t worry there’s plenty of resources online ! I’ll be writing on it soon as well!</p><p>Let’s walk through each of these new lines one by one : -&gt;</p><pre>{connect} from &#39;react-redux&#39;</pre><p>This is a wrapper function that provides access to the redux global state store. This is a very flexible function and for now you can use</p><p><a href="https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options">reactjs/react-redux</a></p><pre>{browserHistory} from &#39;react-router&#39;</pre><p>browserHistory can be used as an alternative to <em>this.context.router</em> to change view state and pass in params as well :</p><p><a href="https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md">reactjs/react-router</a></p><p>With our assumptions in mind, we can piece together how all of this is locking in.</p><pre>componentWillMount(){</pre><pre>if(!this.props.loggedIn){<br>  <br>  browserHistory.push(&#39;/&#39;)</pre><pre>}</pre><p>What this line does is it checks the current login session’s boolean state — which was initially made true when some user signs in with valid credentials. If the session results as invalid (false) the browserHistory object pushes or rather <em>changes</em> the present URL to the home page i.e “/”</p><h4>DO NOTE :</h4><p>This is probably not the best way to authenticate things, leaving a boolean state to true until someone logs out, would be highly advised against (this is all for simplicity).</p><p>The way I currently employ routed authentication, follows a similar process, however — I send out a request to the backend that is tied with a JWT (JSON Web Token) which then interacts with a secret string we would have created on the server side, validates the token and returns a boolean, we then use this boolean as a confirmation. So you can assume that each time the route changes during an existing session, we interact with the server to validate the JWT =&gt; This is one of the many many ways people do it, so feel free to explore around and find/experiment alternatives.</p><pre>componentWillMount(){</pre><pre>//action that validates session with current token stored in state</pre><pre>if(someAction() === true){<br>  <br>  browserHistory.push(&#39;/&#39;)</pre><pre>}</pre><h3>There You Go:</h3><p>I hope this helped you guys, i’ve been meaning to write this for over 3 months now, HOCs are GREAT, i love the concept of it and how it fits so well into the ReactJS and Redux environment. If you have any questions or would like me to better explain something, feel free to shoot me a message.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef98dc2acd6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>