<?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 Unni Krishnan D on Medium]]></title>
        <description><![CDATA[Stories by Unni Krishnan D on Medium]]></description>
        <link>https://medium.com/@unnikrishnand?source=rss-3cae0508dd70------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Fg0pVM6rw_zg43_n.</url>
            <title>Stories by Unni Krishnan D on Medium</title>
            <link>https://medium.com/@unnikrishnand?source=rss-3cae0508dd70------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:44:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@unnikrishnand/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[Implementation of createContext using custom hooks]]></title>
            <link>https://unnikrishnand.medium.com/implementation-of-createcontext-using-custom-hooks-7ecd190cf748?source=rss-3cae0508dd70------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ecd190cf748</guid>
            <category><![CDATA[context]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Unni Krishnan D]]></dc:creator>
            <pubDate>Fri, 06 May 2022 05:38:41 GMT</pubDate>
            <atom:updated>2022-05-06T05:49:28.921Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Prerequisites</strong></h4><p>React knowledge</p><p><strong>Why we need context ?</strong></p><p>Sharing of data across components with out the use of any state management libraries like redux or other storages like localStorage.</p><p><strong>The code</strong></p><p>Assuming we have scaffolded a basic reactjs app using create-react-app</p><p>Create a context (<strong>MyContext.jsx</strong>) in src/context folder</p><pre>import React, { useState } from &quot;react&quot;;<br>const MyContext = React.createContext();</pre><pre>const defaultValue = {<br>   name: &quot;No name defined&quot;, <br>   weapon: &quot;No weapon defined&quot;<br>};</pre><pre>export const MyContextProvider = ({ children, initialData }) =&gt; {</pre><pre>const [value, setValue] = useState(initialData || defaultValue);</pre><pre>const saveValue = (values) =&gt; { setValue(values) };</pre><pre>return (<br>&lt;MyContext.Provider value={{ avengerData: value, saveValue }}&gt;       {children}<br>&lt;/MyContext.Provider&gt;<br>);<br>};</pre><pre>export default MyContext;</pre><p>we have a state variable (<strong>value</strong>)and it change modifier (<strong>setValue</strong>) defined. Using context we are providing the value and the modifier function to its children.</p><p>Now lets create a custom hook (<strong>userAvengers.js</strong>) in src/hooks and import the above context in the hook</p><pre>import { useContext } from &quot;react&quot;;<br>import MyContext from &quot;../context/MyContext&quot;; // import the context</pre><pre>const UseAvenger =  () =&gt; {<br>const context = useContext(MyContext);<br>return context;<br>};<br>export default UseAvenger;</pre><p>Now we can use this context. Here im using this context for the entire application so I&#39;m modifying my src/index.js like this</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import App from &#39;./App&#39;;<br>import { MyContextProvider } from &#39;./context/MyContext&#39;;</pre><pre>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));</pre><pre>const defaultValue = {name: &quot;Captain America&quot;,weapon: &quot;Shield&quot;};</pre><pre>root.render(<br>&lt;MyContextProvider initialData={defaultValue}&gt;<br>    &lt;App /&gt;<br>&lt;/MyContextProvider&gt;<br>);</pre><p>Here we have wrapped the entire application <strong>&lt;App /&gt; </strong>in MyContextProvider and passed a default value as <strong>initialData </strong>to the context provider</p><p>In App.jsx we consumed the context using the custom hook <strong>useAvengers </strong>and we used one more component <strong>AnotherComponent </strong>which modifies the context data</p><p><strong>App.js</strong></p><pre>import UseAvenger from &#39;./hooks/useAvengers&#39;;<br>import AnotherComponent from &#39;./components/AnotherComponent&#39;;</pre><pre>function App() {<br>const { avengerData } = UseAvenger();<br>return (<br>    &lt;div style={{border:&#39;2px solid #F8C565&#39;, padding:&#39;5px&#39;, margin:&#39;5px&#39;}}&gt;</pre><pre>&lt;p&gt;The current  Avenger is &lt;strong&gt;{avengerData.name}&lt;/strong&gt;, and the weapon is &lt;strong&gt;{avengerData.weapon}&lt;/strong&gt;&lt;/p&gt;</pre><pre>&lt;AnotherComponent /&gt;<br>  &lt;/div&gt;<br>);<br>}<br>export default App;</pre><p><strong>AnotherComponent.jsx</strong></p><pre>import UseAvenger from &#39;../hooks/useAvengers&#39;;<br>import React, {useEffect} from &#39;react&#39;;</pre><pre>function AnotherComponent() {<br>const { avengerData, saveValue } = UseAvenger();<br>const changeAvengers = () =&gt; {saveValue({ name: &quot;Tony stark&quot;, weapon: &quot;Arc&quot; });<br>};<br>return (<br>&lt;div style={{border:&#39;2px solid #e3e3e3&#39;, padding:&#39;5px&#39;, margin:&#39;5px&#39;}}&gt;<br>&lt;strong&gt;Another component&lt;/strong&gt;<br>&lt;p&gt;The current  Avenger is &lt;strong&gt;{avengerData.name}&lt;/strong&gt;, and the weapon is &lt;strong&gt;{avengerData.weapon}&lt;/strong&gt;&lt;/p&gt;&lt;div&gt;&lt;button onClick={() =&gt; {changeAvengers()}}&gt;Change&lt;/button&gt;/div&gt;&lt;/div&gt;);<br>}<br>export default AnotherComponent;</pre><p>When we click on the change button we are calling the <strong>changeAvengers </strong>function which in turn calls the <strong>saveValue </strong>function which is a context provider functionality that modifies the context data. When the data is successfully modified both the <strong>App </strong>and <strong>AnotherComponent </strong>will gets the new data.</p><p>Initial load we get the following data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*G_r-KBZb1TtajOkvy0wwGA.png" /></figure><p>After clicking change</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*GWL27OGZqXbyr9OdR0cndw.png" /></figure><p><strong>Conclusion</strong></p><p>A robust way of sharing data across components if you are not using any state management libraries or you have a lot of nested components to pass the props.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ecd190cf748" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript promises for absolute beginners]]></title>
            <link>https://unnikrishnand.medium.com/javascript-promises-for-absolute-beginners-8b5941a579e6?source=rss-3cae0508dd70------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b5941a579e6</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Unni Krishnan D]]></dc:creator>
            <pubDate>Sat, 09 Oct 2021 10:01:44 GMT</pubDate>
            <atom:updated>2021-10-10T04:10:46.351Z</atom:updated>
            <content:encoded><![CDATA[<p>In layman’s term, A Promise is a piece of JavaScript code that represents a completion or failure of an asynchronous operation and its resulting value.</p><p>Eg:</p><pre>let myPromise = aPromiseFunction();</pre><p>Here aPromiseFunction is a Promise object which can return a value at a later point of time which can be either a success or failure.So till that time it acts as a Proxy (A nominee for some other value).</p><p><strong>Structure of a Promise</strong></p><pre>let <strong>myPromise </strong>= new Promise(function(resolveFunction, rejectFunction) {<br>  resolveFunction(); // when successful<br>  rejectFunction();  // when error<br>});</pre><p>And then we can consume the promise like this</p><pre><strong>myPromise</strong>.then(<br>  function(value) { /* code if successful */ },<br>  function(error) { /* code if some error */ }<br>);</pre><p>Here resolveFunction and rejectFunction represents the callbacks corresponding to success and error and it can take payloads correspondingly.</p><p>Lets restructure our Promise</p><pre>let <strong>myPromise </strong>= new Promise(function(resolveFunction, rejectFunction) {<br>  if(someBusinessConditionisTrue()) { <br>     resolveFunction(&quot;OK&quot;); // when successful<br>   }else{<br>     rejectFunction(&quot;ERROR&quot;);  // when error<br>   }<br>});</pre><p>Here someBusinessConditionisTrue is some function that returns true or false in our code.</p><p>And now the consuming part becomes</p><pre><strong>myPromise</strong>.then(<br>  function(value) { console.log(value); }, /* OK */<br>  function(error) { console.log(error); }  /* ERROR */<br>);</pre><p><strong>How to use promise for an async operation</strong></p><p>I have hosted one API at <a href="https://615fcf10f7254d001706821b.mockapi.io/api/v1/users">https://615fcf10f7254d001706821b.mockapi.io/api/v1/users</a> which return an array of user data objects for this example.Let’s use Fetch for async calls.</p><pre>let <strong>userPromise</strong>= new Promise(function(<strong>resolveFunction</strong>, <strong>rejectFunction</strong>) {<br>console.log(&#39;Promise Initializing&#39;);<br>fetch(&#39;<a href="https://615fcf10f7254d001706821b.mockapi.io/api/v1/users&#39;">https://615fcf10f7254d001706821b.mockapi.io/api/v1/users&#39;</a>)<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; <strong>resolveFunction</strong>(data))<br>  .catch((error) =&gt; {<br>   <strong>rejectFunction</strong>(error);<br>});<br>});</pre><p>And at the consuming part</p><pre><strong>userPromise</strong>.then(<br>  function(value) {console.log(value);},<br>  function(error) {console.log(error);}<br>).finally(function(data) { /* This part will always execute either for success or error */<br>console.log(&#39;Promise executed successfully&#39;);<br>});</pre><p>The output console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*hUcJkPD2jwavHBnyzazz3w.png" /></figure><p><strong>Promise methods</strong></p><p>Lets consider the following , we have three promises.</p><pre>let <strong>promise1 </strong>= Promise.resolve(&#39;Hello&#39;);<br>let <strong>promise2 </strong>= Promise.reject(&#39;Reject&#39;);<br>let <strong>promise3</strong>= new Promise(function(resolveFunction, rejectFunction) {<br>console.log(&#39;Promise Initializing&#39;);<br>fetch(&#39;<a href="https://615fcf10f7254d001706821b.mockapi.io/api/v1/users&#39;">https://615fcf10f7254d001706821b.mockapi.io/api/v1/users&#39;</a>)<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; resolveFunction(data))<br>  .catch((error) =&gt; {<br>   rejectFunction(error);<br>});<br>});</pre><p>Now lets create the promise methods</p><p><strong>1.Promise.all</strong></p><p><strong>Promise.all</strong>([promise1, promise2, promise3]).then(values =&gt; {<br>console.log(values);<br>}).catch(d =&gt; {<br>console.log(d);<br>});</p><p>Here Promise.all takes an iterable list of promise data and returns a single promise that resolves to an array of the input promises.It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.In the example <strong>promise2 </strong>is a rejected one so it will be captured in the catch block.And the output will be <strong>Reject</strong>. and if suppose <strong>promise2 </strong>returns as a resolved one like</p><p>let <strong>promise2 </strong>= Promise.resolve(&#39;Dont reject&#39;);</p><p>then the output will be :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rk8yZ6eAAYhr_5xdRuRGVQ.png" /><figcaption>Promise All</figcaption></figure><p><strong>2.Promise.race</strong></p><p>The <strong>Promise.race</strong> method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.</p><p>Lets modify our promises a little bit</p><pre><strong>let promise1 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(resolve, 500, &#39;Hello&#39;);<br>});</strong><br>let <strong>promise2 </strong>= Promise.resolve(&#39;Dont reject&#39;);<br>let <strong>promise3</strong>= new Promise(function(resolveFunction, rejectFunction) {<br>console.log(&#39;Promise Initializing&#39;);<br>fetch(&#39;<a href="https://615fcf10f7254d001706821b.mockapi.io/api/v1/users&#39;">https://615fcf10f7254d001706821b.mockapi.io/api/v1/users&#39;</a>)<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; resolveFunction(data))<br>  .catch((error) =&gt; {<br>   rejectFunction(error);<br>});<br>});</pre><p><strong>Promise.race</strong>([promise1, promise2, promise3]).then(values =&gt; {<br>console.log(values);<br>}).catch(values =&gt; {<br>console.log(values);<br>});</p><p>The output will be <strong>promise2 </strong>(<strong>Dont reject</strong>)as it will be resolving or rejecting faster than the other two:</p><p><strong>3.Promise.any</strong></p><p>Promise.any takes an iterable of the Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise.</p><p>Our previous example with some changes to <strong>promise1 </strong>and <strong>promise 2</strong></p><pre><strong>let promise1 = </strong><strong>Promise.reject(&#39;Reject 1&#39;);<br></strong><strong>let promise2 = Promise.resolve(&#39;Resolve 2&#39;);</strong><br>let <strong>promise3</strong>= new Promise(function(resolveFunction, rejectFunction) {<br>console.log(&#39;Promise Initializing&#39;);<br>fetch(&#39;<a href="https://615fcf10f7254d001706821b.mockapi.io/api/v1/users&#39;">https://615fcf10f7254d001706821b.mockapi.io/api/v1/users&#39;</a>)<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; resolveFunction(data))<br>  .catch((error) =&gt; {<br>   rejectFunction(error);<br>});<br>});</pre><pre>Promise.any([promise1, promise2, promise3]).then(values =&gt; {<br>console.log(values);<br>}).catch(values =&gt; {<br>console.log(values);<br>});</pre><p>The output will be <strong>promise2 (Resolve 2) </strong>as <strong>promise1 </strong>is a rejected one and <strong>promise3 </strong>is yet to fulfill.</p><p><strong>4.Promise.allSettled</strong></p><p>The <strong>Promise.allSettled()</strong> method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.</p><pre>Promise.<strong>allSettled</strong>([promise1, promise2, promise3]).then(values =&gt; {<br>console.log(values);<br>}).catch(values =&gt; {<br>console.log(values);<br>});</pre><p>And the output will be :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*PKumBgCl24iKBnrxL07ofw.png" /></figure><p><strong>Conclusion</strong></p><p>We have gone through the basics of a Promise, its constructor ,object and the most important methods available with it.</p><p>Ill be publishing the same for Observables also :)</p><p>Reference : <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b5941a579e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The real use of useEffect in ReactJS]]></title>
            <link>https://unnikrishnand.medium.com/the-real-use-of-useeffect-in-reactjs-a8152f0f9a1f?source=rss-3cae0508dd70------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8152f0f9a1f</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook-useeffect]]></category>
            <dc:creator><![CDATA[Unni Krishnan D]]></dc:creator>
            <pubDate>Sun, 13 Jun 2021 06:42:00 GMT</pubDate>
            <atom:updated>2021-06-13T06:45:22.260Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Yes you are right ! , we are here to find out the real use of useEffect hook in ReactJS</blockquote><p><strong>Prerequisites</strong><br>1. Ofcourse its ReactJS ! , The functional programming paradigm and lastly at least a basic understanding of components in reactjs.</p><p><strong>What is useEffect</strong></p><p>UseEffect is a very powerful hook that can introduce the life cycle methods of a Reactjs class based components in functional components and also it is used to handle side effect functionalities.In functional programming we dont have class as a base for creating components.Everything is a function here (like the good ‘ol vanilla JavaScript days)</p><p><strong>useEffect</strong> is a hook for encapsulating code that has ‘side effects,’ and is like a combination of componentDidMount , componentDidUpdate , and componentWillUnmount</p><p><strong>Lets dig in with a practical example :)</strong></p><p>The example consists of two components (parent and child) and a lot of useEffect hooks in the child component to demonstrate each of the lifecycle hooks.</p><p><strong>Parent component</strong></p><pre><em>// parent component</em></pre><pre>import React, { useState } from &quot;react&quot;;</pre><pre>import AnotherComponent from &quot;./AnotherComponent&quot;;</pre><pre>function <strong>UseEffectExample</strong>() {</pre><pre>const [v1, <strong>setV1</strong>] = <strong>useState</strong>(&quot;&quot;);</pre><pre>const [v2, <strong>setV2</strong>] = <strong>useState</strong>(&quot;&quot;);</pre><pre>return (</pre><pre>&lt;React.Fragment&gt;</pre><pre>&lt;p&gt;Prop 1&lt;input <em>type</em>=&quot;text&quot; <em>value</em>={v1} <em>onChange</em>={(evt) =&gt; {<strong>setV1</strong>(evt.target.value)}} /&gt;&lt;/p&gt;</pre><pre>&lt;p&gt;Prop 2&lt;input <em>type</em>=&quot;text&quot; <em>value</em>={v2} <em>onChange</em>={(evt) =&gt; {<strong>setV2</strong>(evt.target.value)}} /&gt;&lt;/p&gt;</pre><pre>&lt;AnotherComponent <em>prop1</em>={v1} <em>prop2</em>={v2} /&gt;</pre><pre>&lt;/React.Fragment&gt;</pre><pre>);<br>}<br>export default <strong>UseEffectExample</strong>;</pre><p><strong>Child component</strong></p><pre><em>// child component</em></pre><pre>import React, { useEffect } from &quot;react&quot;;</pre><pre>function <strong>AnotherComponent</strong>(props) {</pre><pre>const {</pre><pre>prop1,</pre><pre>prop2</pre><pre>} = props;</pre><pre><strong>useEffect</strong>(() =&gt; {</pre><pre>console.<strong>log</strong>(&#39;This will always trigger , on load and prop change ,{{ComponentDidMount}}&#39;);</pre><pre>})</pre><pre><strong>useEffect</strong>(() =&gt; {</pre><pre>console.<strong>log</strong>(&#39;This will trigger only once {{ComponentWillUnMount}}&#39;);</pre><pre>}, [])</pre><pre><strong>useEffect</strong>(() =&gt; {</pre><pre>console.<strong>log</strong>(&#39;This will trigger when prop1 changes {{componentDidUpdate}}&#39;);</pre><pre>}, [prop1])</pre><pre><strong>useEffect</strong>(() =&gt; {</pre><pre>console.<strong>log</strong>(&#39;This will trigger when prop2 changes  {{componentDidUpdate}}&#39;);</pre><pre>}, [prop2])</pre><pre>return(</pre><pre>&lt;p&gt;Another one with props: {prop1}, {prop2}&lt;/p&gt;</pre><pre>)}</pre><pre>export default <strong>AnotherComponent</strong>;</pre><p>So what we did was we created two components , a parent component with two text inputs and the corresponding state values.A child component is there to accept the values as parameters.In the child component we have written four different useEffects representing the lifecycle methods.</p><p>When the loading the app , this will be the output in the console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*gbEYED_9qM-krsHlwZXBrw.png" /></figure><p>The console will trigger from all the useEffect blocks.The first useEffect block will behave as componentDidMount so it will trigger everytime the component is called , it even triggers both both props (prop1 and prop2 because the value is set to “” for both props initially).</p><pre><strong>useEffect</strong>(() =&gt; {console.<strong>log</strong>(&#39;This will always trigger , on load and prop change ,{{ComponentDidMount}}&#39;);})</pre><p>The second useEffect block with a [] as dependency will run only once as it indicates all the effects are applied here.</p><pre><strong>useEffect</strong>(() =&gt; {console.<strong>log</strong>(&#39;This will trigger only once {{ComponentWillUnMount}}&#39;);}, [])</pre><p>The third and fourth useEffect blocks are exclusively linked to that dependency prop change</p><pre><strong>useEffect</strong>(() =&gt; {console.<strong>log</strong>(&#39;This will trigger when prop2 changes {{componentDidUpdate}}&#39;);}, [prop2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*ll5Gon4mt-hd_VhXe0AOkQ.png" /></figure><p><strong>Conclusion</strong></p><p>So basically what we did was we created multiple useEffect hooks to demonstrate the different life cycle methods with respect to components.The dependency injection in useEffect is a great way to reduce unnecessary component reloads and thereby increasing the app performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8152f0f9a1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of React Redux data store with React Hooks and functional components]]></title>
            <link>https://unnikrishnand.medium.com/implementation-of-react-redux-data-store-with-react-hooks-and-functional-components-80082fbd2597?source=rss-3cae0508dd70------2</link>
            <guid isPermaLink="false">https://medium.com/p/80082fbd2597</guid>
            <category><![CDATA[react-hook-useeffect]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Unni Krishnan D]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 09:42:53 GMT</pubDate>
            <atom:updated>2021-02-22T09:42:53.517Z</atom:updated>
            <content:encoded><![CDATA[<p>With the release of React 16.8 there is a new feature that will replace the redundant and hard to maintain React life cycle methods like ComponentDidMount , ComponentWillMount etc.React has moved from Class to functional components.In this tutorial ill be explaining how you can get data from redux store in your functional component.</p><p><strong>The Redux Architecture</strong></p><p>The concepts of redux is exactly the same as class with React Hooks and functional components.We create a centralized data store (A collection of reducers).Actions are there which act as a communication layer between your component and store and finally reducers which practically holds the data.</p><p><strong>The packages required</strong></p><p><em>axios </em>: For your API calls.</p><p><em>react-redux</em> : Core functionality for redux.</p><p><em>redux</em>: For creation of store.</p><p>Simply execute this command from your root folder <br>npm i axios react-redux redux --save-dev</p><p>What im trying to achieve is to get a list of users through an API call , store it in store and retrieve the data in one of the component.</p><p><strong>The code part</strong></p><p>In your index.js root file add these changes highlighted in bold text</p><pre>import React from &#39;react&#39;;</pre><pre>import ReactDOM from &#39;react-dom&#39;;</pre><pre>import &#39;./index.css&#39;;</pre><pre><strong>import { createStore } from &#39;redux&#39;;</strong></pre><pre><strong>import { Provider } from &#39;react-redux&#39;;</strong></pre><pre><strong>import UserComponent from &#39;./App&#39;;</strong></pre><pre><strong>import rootReducers from &#39;./reducers&#39;;</strong></pre><pre><strong>const store = createStore(rootReducers)</strong></pre><pre>ReactDOM.render(</pre><pre><strong>&lt;Provider store={store}&gt;</strong></pre><pre>&lt;UserComponent /&gt;</pre><pre><strong>&lt;/Provider&gt;,</strong></pre><pre>document.getElementById(&#39;root&#39;)</pre><pre>)</pre><p>Usercomponent : Our functional component where we are getting this data.</p><p>createStore: This helps to create our store. we need to pass a reducer or a collection of reducer to it as a parameter.</p><p>Provider: A higher order component (HOC) responsible for making the store available across the entire app.</p><p>rootReducers: your list of reducers , we will come to this later</p><p><strong>Configuration</strong></p><p>Lets create a config.js file and store our url end points (Config.js)</p><pre>const config = {</pre><pre>baseUrl: &#39;https://jsonplaceholder.typicode.com/&#39;,</pre><pre>endPoints:{users: &#39;users&#39;,}<br>};</pre><pre>export default config;</pre><p>A Communication layer responsible for API (Communication.js)</p><pre>import axios from &#39;axios&#39;;<br>import config from &#39;../config&#39;;</pre><pre>const Communication = {</pre><pre>getMethod(endpoint) {<br>return axios.get(config.baseUrl + endpoint).then(response =&gt; {    return response.data; })<br>}};<br>export default Communication;</pre><p>A service layer (Userservice.js)</p><p>As we only have one API , we need only one service file (Userservice.js).Ill explain the ‘dispatch’ in detail in the next section.So basically this is a Service Object which uses Axios (Communication.js) for API call.</p><pre>import Communication from &#39;./Communication&#39;;</pre><pre>import config from &#39;../config&#39;;</pre><pre>const UserService = { </pre><pre>loadUsers(dispatch) {</pre><pre>dispatch({type: &#39;LOAD_USERS&#39;,payload: null})</pre><pre>Communication.getMethod(config.endPoints.users).then(users =&gt; {</pre><pre>dispatch({type: &#39;GET_USERS&#39;,payload: users})</pre><pre>}).catch(() =&gt; {<br>dispatch({type: &#39;ERROR_USERS&#39;,payload: null})<br>}).finally(() =&gt; {})</pre><pre>}}<br>export default UserService;</pre><p>The reducers (userReducer.js)</p><p>As we are managing only one api call , we need only one reducer.Basically reducer is a function that returns an object based on a switch statement.</p><pre>const initialState = {</pre><pre>usersList : [],</pre><pre>loading : true,</pre><pre>error: false,</pre><pre>};</pre><pre>function usersReducer(state = initialState, action) {</pre><pre>switch (action.type) {</pre><pre>case &#39;LOAD_USERS&#39;:</pre><pre>return { ...state, usersList:[], error: false, loading: true }</pre><pre>case &#39;GET_USERS&#39;:</pre><pre>return { ...state, usersList: action.payload, error: false, loading: false }</pre><pre>case &#39;ERROR_USERS&#39;:</pre><pre>return { ...state, usersList: [], error: true, loading: false }</pre><pre>default:</pre><pre>return state;</pre><pre>}</pre><pre>};</pre><pre>export default usersReducer;</pre><p>We need to combine this reducers with other reducers.Here we only have one reducer.But ideally we have more than one API call in any project so we can use like this</p><pre>import {combineReducers} from &#39;redux&#39;;<br>import usersReducer from &#39;./usersReducer&#39;;</pre><pre>// other reducers needs to import here</pre><pre>const rootReducers = combineReducers({</pre><pre>usersData : usersReducer<br>// if there are other reducers , we can add here one by one</pre><pre>});</pre><pre>export default rootReducers;</pre><p>So rootReducers hold your entire list of reducers in a key value pair.</p><p>Finally The folder structure will look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVmlRUWT8e-f2G7vtviZng.png" /></figure><p>So we created API layer (Communication.js),Service layer (userService.js).The last step is from the component we need to call the API, store it in store and populate in UI.</p><p>import the required packages in UserComponent</p><pre>import { useDispatch, useSelector } from &#39;react-redux&#39;;<br>import UserService from &#39;./services/Userservice&#39;;</pre><p>Call the userService from useEffect hook</p><pre>export const UserComponent = () =&gt; {<br>const dispatch = useDispatch();</pre><pre>// Slice the data from the store using useSelector<br>const usersInfo = useSelector((state) =&gt; state.usersData);</pre><pre>useEffect(() =&gt; {<br>   UserService.loadUsers(dispatch);<br>}, [dispatch])</pre><p>So what we did was we accessed data from userReducer using useSelector.The usersData key is what we have given in reducers/index.js</p><p>Finally we call the userService in the useEffect hook and pass the dispatch function to it.In the user service we keep certain checkpoints and during this checkpoint we dispatch a call that will alert the userReducer about its current status.For eg:</p><pre>dispatch({type: &#39;LOAD_USERS&#39;,payload: null})</pre><p>This will alert the reducer that the API call is about to make.In the userReducer, the switch statement will return the object corresponding to ‘LOAD_USERS’.The user component will render based on that data supplied by the reducer.</p><pre>dispatch({type: &#39;GET_USERS&#39;,payload: users})</pre><p>This will return the data that we are getting from the API back to reducer.The userReducer in turn returns the corresponding object for ‘GET_USERS’</p><pre>case &#39;GET_USERS&#39;:<br>return { ...state, usersList: action.payload, error: false, loading: false }</pre><p>The additional keys error, loading can be used to determine the state of the component (loading : show a progress bar, error : show an error status etc)</p><p>Finally the component will look like this</p><pre>import React, { useEffect } from &#39;react&#39;;<br>import { useDispatch, useSelector } from &#39;react-redux&#39;;<br>import loader from &#39;./assets/loader.gif&#39;;<br>import UserService from &#39;./services/Userservice&#39;;<br>import &#39;./App.css&#39;;</pre><pre>export const UserComponent = () =&gt; {</pre><pre>const dispatch = useDispatch();</pre><pre>const usersInfo = useSelector((state) =&gt; state.usersData);</pre><pre>useEffect(() =&gt; { UserService.loadUsers(dispatch); }, [dispatch])</pre><pre><br>const errorContainer = () =&gt; {return &lt;div&gt;ERROR IN API&lt;/div&gt;;}</pre><pre>const showLoader = () =&gt; {return &lt;div&gt;&lt;img src={loader} alt=&quot;loading ...&quot; title =&quot;loading ...&quot;/&gt;&lt;/div&gt;;}</pre><pre>const renderData = (usersInfo) =&gt; { return usersInfo.error ? errorContainer():</pre><pre>&lt;div className=&quot;container&quot;&gt;<br> &lt;div className=&quot;header&quot;&gt;&lt;div&gt;NAME&lt;/div&gt;&lt;div&gt;EMAIL&lt;/div&gt;&lt;div&gt;PHONE&lt;/div&gt;&lt;div&gt;WEBSITE&lt;/div&gt;&lt;/div&gt;</pre><pre>{usersInfo.usersList.map((user, index) =&gt;<br>&lt;div className=&quot;row&quot; key={index}&gt;&lt;div&gt; { user.name } &lt;/div&gt;</pre><pre>&lt;div&gt;{ user.email }&lt;/div&gt;<br>&lt;div&gt;{ user.phone } &lt;/div&gt;<br>&lt;div&gt;{ user.website } &lt;/div&gt;<br>&lt;/div&gt;)}</pre><pre>&lt;/div&gt;</pre><pre>}<br>return (<br>usersInfo.loading ? showLoader() : renderData(usersInfo)<br>)}<br>export default UserComponent;</pre><p><strong>Summarizing the implementation</strong><br>What we did is we created a component and from that component we called a service which communicates the data back to one of the reducers.The components binded to that reducer will automatically reloads when ever a new data comes in the reducer.At any given point the data in userReducer is same across all the components.In this way data consistency is maintained.</p><p>The entire example is available in github.</p><p><a href="https://github.com/ubercooluk/redux-with-hooks.git">https://github.com/ubercooluk/redux-with-hooks.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80082fbd2597" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An elementary view of Ngrx store with Angular 8]]></title>
            <link>https://unnikrishnand.medium.com/an-elementary-view-of-ngrx-store-with-angular-8-b81636dca417?source=rss-3cae0508dd70------2</link>
            <guid isPermaLink="false">https://medium.com/p/b81636dca417</guid>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[angular8]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Unni Krishnan D]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 08:20:58 GMT</pubDate>
            <atom:updated>2020-05-01T13:31:34.009Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Ngrx store with Angular 8</h3><p>First things first,this article is intended for people who are familiar with Angular and MVVM architecture, but yet to try ngrx in their application.</p><p><em>What im trying to put is</em></p><ol><li>How the data flows between components with the help of actions &amp; reducers.</li><li>Handling a same set of data in different components from a single store</li></ol><p><em>What im not trying to say is (at least for now :))</em></p><ol><li>All those fancy stuff with regards to ngrx (Effects,Selectors etc)</li></ol><h3>Synopsis</h3><p>Creating a list of data (user information) with Angular 8 &amp; using ngrx as a data store. Im using Rxjs for subscribing the data with the components.</p><h3><strong>Creating the project</strong></h3><p>Bootstrapping (Installing angular cli and creating a new project)</p><p>npm i @angular/cli -g</p><p>ng new angular-ngrx-app</p><p>Adding ngrx store and rxjs</p><p>npm i @ngrx/store</p><p>npm i rxjs</p><h3>Folder structure</h3><p>Add a folder to the existing code base like in the screenshot. Im using this folder <strong>(store)</strong>to hold all my store related files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jH4nZisWkGaTPNxYc-vCPQ.png" /></figure><p><strong>actions </strong>: It contains functions which can trigger a manipulation to the store.This acts as a communication channel between the components and store.It takes two parameters <strong>payload</strong> (optional) which is the data and <strong>type</strong> which acts as a unique identifier to distinguish the action.</p><p><strong>models</strong>(optional) : Contains interfaces that defines the structure of the data.</p><p><strong>reducers : </strong>This is where our data resides.A store is a collection of reducers.The component triggers the action with payload and it is captured in a reducer based on the action type.All the data manipulations happens at this layer.</p><h3><strong>Creating the models</strong></h3><p>Inside models , we will create the structure for our data.</p><p><strong>user.model.ts</strong></p><pre>//The user model interface</pre><pre>export interface UserAdd {</pre><pre>id : string,<br>name : string,<br>email : string,<br>age : number,<br>address : string<br>}</pre><p><strong>app.model.ts<br></strong>app model is an array of user data</p><pre>import { UserAdd } from &#39;./users.model&#39;;</pre><pre>export interface AppState {<br>readonly users: Array&lt;UserAdd&gt;<br>}</pre><p>Now lets create actions inside actions folder<br><strong>user.action.ts</strong></p><pre>import { Action } from &#39;@ngrx/store&#39;;<br>import { UserAdd } from &#39;../models/users.model&#39;;</pre><pre>export enum UserActionTypes  {</pre><pre>//add</pre><pre>ADD_USER = &#39;[USER] ADD&#39;,</pre><pre>//delete</pre><pre>DELETE_USER = &#39;[USER] DELETE&#39;,</pre><pre>}</pre><pre>export class AddUserAction implements Action {</pre><pre>readonly type = UserActionTypes.ADD_USER;</pre><pre>constructor(public payload : UserAdd) {}</pre><pre>}</pre><pre>export class DeleteUserAction implements Action {</pre><pre>readonly type = UserActionTypes.DELETE_USER;</pre><pre>constructor(public payload : string) {}</pre><pre>}<br>export type UserActions = AddUserAction | DeleteUserAction;</pre><p>We have two functionalities User add and delete and each of its corresponding actions <strong>AddUserAction</strong> and <strong>DeleteUserAction </strong>which implements Action from ngrx/store .The <strong>UserActionTypes </strong>is an enum which uniquely identifies action types.</p><p><strong>finally creating the reducer</strong></p><pre>import { UserAdd} from &#39;../models/users.model&#39;;<br>import {UserActions, UserActionTypes} from &#39;../actions/users.action&#39;</pre><pre>//initial store data<br>const initialState : Array&lt;UserAdd&gt; = [<br>{<br>id : &quot;123-456-789&quot;,name : &quot;John doe&quot;,age : 32,address : &quot;Hello world&quot;,email : &quot;something@gmail.com&quot;<br>}<br>]<br>// The only reducer we are using for this example</pre><pre>export function UserReducer(state: Array&lt;UserAdd&gt; = initialState,action :UserActions){</pre><pre>switch(action.type) {<br>   case UserActionTypes.ADD_USER :<br>       return [...state,action.payload];</pre><pre>   case UserActionTypes.DELETE_USER:<br>       return state.filter(item =&gt; item.id !== action.payload);<br>   default:<br>       return state;<br>}</pre><pre>};</pre><p>The <strong>initialState </strong>represents the initial state of the store.We have two functionalities in our reducer if the action triggers a <strong>UserActionTypes.ADD_USER </strong>then we will add the payload to our reducer and if its a <strong>UserActionTypes.DELETE_USER </strong>then we will filter out the store with the deleted data.</p><h4><strong>Plugging store in app.module.ts</strong></h4><pre>//importing the store</pre><pre>import { StoreModule } from &#39;@ngrx/store&#39;;</pre><pre>import { UserReducer } from &#39;./store/reducers&#39;;</pre><p>And in imports add</p><pre>imports: [</pre><pre>BrowserModule,FormsModule,AppRoutingModule,<br>//Binding the store.The store contains only a single reducer</pre><pre>StoreModule.forRoot({<br>users : UserReducer<br>})<br>],</pre><h3><strong>User component</strong></h3><p><strong>app.component.ts</strong></p><p>importing models</p><pre>import { AppState } from &#39;./store/models/app.model&#39;;<br>import {UserAdd } from &#39;./store/models/users.model&#39;;</pre><p>Importing actions</p><pre>import { DeleteUserAction, AddUserAction} from &#39;./store/actions/users.action&#39;</pre><p>We use Observable from rxjs for subscribing store with components</p><pre>import { Observable } from &#39;rxjs&#39;;</pre><p>In the component we will define our userlist as</p><pre>userslist: Observable&lt;Array&lt;UserAdd&gt;&gt;;</pre><p>Initializing user input fields</p><pre>userinput = {name :&#39;&#39;,age:0,email:&#39;&#39;,address:&#39;&#39;,id :&#39;&#39;}</pre><p>Injecting store and retrieving current data from reducer</p><pre>constructor(private store: Store&lt;AppState&gt;) { }</pre><pre>ngOnInit() {<br>this.userslist = this.store.select(store =&gt; store.users);<br>}</pre><p><strong>Add and delete functionality</strong></p><pre>saveUser() {</pre><pre>this.userinput.id = uuid();</pre><pre>this.store.dispatch(new AddUserAction(this.userinput));<br>//clearing the input fields<br>this.userinput = {name :&#39;&#39;,age:0,email:&#39;&#39;,address:&#39;&#39;,id :uuid()}</pre><pre>}<br>deleteUser(id){</pre><pre>this.store.dispatch(new DeleteUserAction(id));</pre><pre>}</pre><p>The UI template</p><pre>&lt;div id=&quot;wrapper&quot;&gt;</pre><pre>&lt;div id=&quot;users-list&quot;&gt;</pre><pre>&lt;div id=&quot;list&quot;&gt;</pre><pre>&lt;h2&gt;Users List (App Component)&lt;/h2&gt;</pre><pre>&lt;div class=&quot;container&quot;&gt;</pre><pre>&lt;div class=&quot;headers&quot;&gt;</pre><pre>&lt;div&gt;Name&lt;/div&gt;</pre><pre>&lt;div&gt;Age&lt;/div&gt;</pre><pre>&lt;div&gt;Address&lt;/div&gt;</pre><pre>&lt;div&gt;Email&lt;/div&gt;</pre><pre>&lt;div&gt;&lt;a href=&quot;javascript:void(0);&quot; (click)=&quot;toggleUser()&quot;&gt;ADD USER&lt;/a&gt;&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;headers&quot; *ngIf=showadd&gt;</pre><pre>&lt;div&gt;&lt;input type=&quot;text&quot; [(ngModel)]=&quot;userinput.name&quot; /&gt;&lt;/div&gt;</pre><pre>&lt;div&gt;&lt;input type=&quot;text&quot; [(ngModel)]=&quot;userinput.age&quot; /&gt;&lt;/div&gt;</pre><pre>&lt;div&gt;&lt;input type=&quot;text&quot; [(ngModel)]=&quot;userinput.address&quot; /&gt;&lt;/div&gt;</pre><pre>&lt;div&gt;&lt;input type=&quot;text&quot; [(ngModel)]=&quot;userinput.email&quot; /&gt;&lt;/div&gt;</pre><pre>&lt;div&gt;&lt;input type=&quot;button&quot; value=&quot;Save User&quot; (click)=&quot;saveUser()&quot; /&gt;&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;item&quot; *ngFor=&quot;let user of userslist | async&quot;&gt;</pre><pre>&lt;div&gt;{{ user.name }}&lt;/div&gt;</pre><pre>&lt;div&gt;{{ user.age }}&lt;/div&gt;</pre><pre>&lt;div&gt;{{ user.address }}&lt;/div&gt;</pre><pre>&lt;div&gt;{{ user.email }}&lt;/div&gt;</pre><pre>&lt;div&gt;&lt;a href=&quot;javascript:void(0);&quot; (click)=&quot;deleteUser(user.id)&quot;&gt;DELETE&lt;/a&gt;&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;testcomponent&gt;&lt;/testcomponent&gt;</pre><pre>&lt;/div&gt;</pre><p><strong>&lt;testcomponent&gt; </strong>is another component that has an observable subscribed to the same store.It also has a view template that displays the data.</p><pre>export class TestComponent implements OnInit {</pre><pre>userslist: Observable&lt;Array&lt;UserAdd&gt;&gt;;</pre><pre>constructor(private store: Store&lt;AppState&gt;) { }</pre><pre>ngOnInit() {</pre><pre>this.userslist = this.store.select(store =&gt; store.users);</pre><pre>}}</pre><p><strong>test.component.html</strong></p><pre>&lt;div id=&quot;list&quot;&gt;</pre><pre>&lt;h4&gt;Another component using the same store data (Test component)&lt;/h4&gt;</pre><pre>&lt;ul&gt;</pre><pre>&lt;li *ngFor=&quot;let user of userslist | async&quot;&gt;</pre><pre>&lt;span&gt;{{ user.name }}&lt;/span&gt;&lt;span&gt;-&lt;/span&gt;<br>&lt;span&gt;{{ user.email }}&lt;/span&gt;</pre><pre>&lt;/li&gt;</pre><pre>&lt;/ul&gt;</pre><pre>&lt;/div&gt;</pre><blockquote>The point is whenever there is a update happens in the store(Add/Delete) it will reflect in both the components.Whenever there is a store update observable can detect the change and update in the respective components.</blockquote><p>With a touch of css, the app looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0brDMMWPxl4MqkHRWjRTJA.png" /></figure><p>Source code is available at</p><p><a href="https://github.com/ubercooluk/angular-ngrx-app/">https://github.com/ubercooluk/angular-ngrx-app</a></p><p>Clone it ,</p><p><strong><em>npm i</em></strong></p><p>and finally <strong><em>npm run start</em></strong></p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b81636dca417" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VueJs with vuex — for absolute beginners]]></title>
            <link>https://unnikrishnand.medium.com/vuejs-with-vuex-for-absolute-beginners-351a0b2deaea?source=rss-3cae0508dd70------2</link>
            <guid isPermaLink="false">https://medium.com/p/351a0b2deaea</guid>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Unni Krishnan D]]></dc:creator>
            <pubDate>Sun, 10 Mar 2019 10:49:09 GMT</pubDate>
            <atom:updated>2019-03-10T14:50:19.643Z</atom:updated>
            <content:encoded><![CDATA[<h3>VueJs with vuex — for absolute beginners</h3><p>For every single page application there must be a store for optimal way of data sharing between components.For Reactjs we have redux/flux and for Angular we have ngrx. For Vuejs we have vuex.</p><p>Before you proceed you should have a basic understanding of Vuejs or at least the concept about Model–view–viewmodel (MVVM).We will be having components ,views and styles like every SPA frameworks.Ill be covering vuex from scratch so no prior knowledge in vuex is required.</p><p><strong><em>What is a store ?</em></strong></p><p>A store as for every single page application is a single point of truth(simply data).It provides API’s for modifying the data in the store. <strong>Vuex</strong> is a state management pattern and library for Vuejs applications. It serves as a centralized store for all the components in an application.</p><p><strong><em>Installation of vuex</em></strong></p><p>Assuming you have a base vuejs application.Simply execute this command within the project.</p><blockquote>npm install vuex</blockquote><p>Structure of Vuex store</p><p>In the root folder of your application create this file and name it as <strong>store.js</strong></p><pre>import Vuex from ‘vuex’<br>import Vue from ‘vue’</pre><pre>Vue.use(Vuex)</pre><pre>export default new Vuex.Store({</pre><pre>state: {</pre><pre>},</pre><pre>getters:{</pre><pre>},</pre><pre>mutations: {</pre><pre>},</pre><pre>actions:{</pre><pre>}</pre><pre>})</pre><p>And in this main.js file where all the bootstrapping is done add this line where store is the store.js file</p><pre>import store from ‘./store’</pre><p>and in the bootstrapping section</p><pre>new Vue({</pre><pre>store, /** Add this line **/</pre><pre>render: h =&gt; h(App),</pre><pre>}).$mount(‘#app’)</pre><p>Now we have successfully imported store in our application.Lets go through the different sections in the store.js</p><p><strong>state </strong>: It holds all the data for our application.We can even set the initial state of data here for example</p><pre>state: {<br>   userlist : [],<br>   showpopup :false,<br>   listdata : [],<br>},</pre><p><strong>getters </strong>: Computed properties of data is stored here.For example we want to get the count of all users in the store.Simply write</p><pre>getters:{<br>totalUsers : state =&gt; { return state.userlist.length },<br>}</pre><p><strong>mutations</strong>: Functions to manipulate store is written here.We will come to that later in detail.</p><p><strong>actions</strong> : Actions are similar to <strong>mutations</strong>, the differences being that:</p><ul><li>Instead of mutating the state, actions commit mutations.</li><li>Actions can contain arbitrary asynchronous operations.</li></ul><p>Now lets move to our application and what we are trying to achieve.Our application on initial load (more specifically on load of a component) will fetch some data from an API and stores it in the vuex store.We read the same data from the store and do all the manipulations with it.</p><p><strong><em>The API part</em></strong></p><pre>import axios from &#39;axios&#39;</pre><pre>export default {</pre><pre>getUsers(){</pre><pre>return axios.get(&#39;/users&#39;)</pre><pre>.then(response =&gt; {</pre><pre>return response.data;</pre><pre>})<br>}<br>}</pre><p>Name the file as <strong>UserApi.js</strong>.we are using axios for API calls and dont forget to add this line in main.js</p><pre><br>axios.defaults.baseURL = ‘https://jsonplaceholder.typicode.com&#39;</pre><p>so the url will be <a href="https://jsonplaceholder.typicode.com/"><strong>https://jsonplaceholder.typicode.com</strong></a><strong>/users</strong></p><p><strong><em>The component part</em></strong></p><pre>// Import the above API file in your component<br>import UserApi from ‘../services/UserApi’</pre><p>Lets call this API in the <strong>created </strong>life cycle hook of vuejs</p><pre>created() { // this is a life cycle hook</pre><pre>UserApi.getUsers().then(users =&gt; {</pre><pre>this.addUser(users); //we will come to this function later</pre><pre>})</pre><pre>.catch()</pre><pre>.finally(() =&gt; {</pre><pre>})</pre><pre>}</pre><p>Now we have to use helper functions of vuex to retrieve and set data from store.<br>In our component we have to import this</p><pre>import { mapMutations, mapState, mapGetters} from ‘vuex’</pre><p>These helpers are used to map store with components (mutations,state and getters)</p><p>Lets get back to our <strong>store.js and add our mutations,getters and states</strong></p><pre>import Vue from &#39;vue&#39;</pre><pre>import Vuex from &#39;vuex&#39;</pre><pre>Vue.use(Vuex)</pre><pre>export default new Vuex.Store({</pre><pre>state: {</pre><pre>users:[] // we are displaying a list of users</pre><pre>},</pre><pre>getters:{<br>//getter for total number of users</pre><pre>totalUsers : state =&gt; {</pre><pre>return state.users.length </pre><pre>},<br>//getter for getting the Max id from the user list ,The user list is a JSON and it has a field id.</pre><pre>maxId : state =&gt; {</pre><pre>return Math.max(...state.users.map(o =&gt; o.id), 0) + 1;</pre><pre>}</pre><pre>},</pre><pre>mutations: {<br>//Add user to the existing array</pre><pre>ADD_USER:(state,name) =&gt;{</pre><pre>state.users.push(...name);</pre><pre>},<br>//Remove user from the user list</pre><pre>REMOVE_USER:(state,index) =&gt;{</pre><pre>state.users.splice(index,1);</pre><pre>},</pre><pre>},</pre><pre>actions:{</pre><pre>//we dont have any actions for this example</pre><pre>}</pre><pre>})</pre><p>Again in our component and in the life cycle hook <strong>computed </strong>add this</p><pre>computed: {</pre><pre>...mapState([</pre><pre>     &#39;users&#39; // this is the variable we are initializing in the state section of store<br>]),</pre><pre>...mapGetters([<br>      // The getter function names<br>      &#39;maxId&#39;,<br>      &#39;totalUsers&#39;<br>])</pre><pre>},</pre><p>Again in our component and in the life cycle hook <strong>methods </strong>add this</p><pre>methods: {<br>//The name of functions in the mutation section in the store.js<br> …mapMutations([<br>   ‘ADD_USER’,<br>   ‘REMOVE_USER’,<br>]),<br>}</pre><p>Now we have added all the code related to store.js. Now its time to call and utilize them.Previously we had UserApi which calls the API on page load.We are storing the response in our store.</p><pre>created() {</pre><pre>UserApi.getUsers().then(users =&gt; {</pre><pre>this.addUser(users);//This function adds the API result to our store</pre><pre>}).catch()</pre><pre>.finally(() =&gt; {</pre><pre>})</pre><pre>},<br>methods() {<br> addUser:function(data){<br>  // data is coming from API<br> // ADD_USER is a mutation function.It is now available for calling   // because we have used mapMutations to bind that with component   this.ADD_USER(data)<br> }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*GUNrqj_8e2r7z2HArtpdow.png" /><figcaption>User API data</figcaption></figure><p><strong><em>Binding the store data with template</em></strong></p><pre><br>&lt;div v-for=”(user,index) in users” class=”row” v-bind:key=user.id&gt;</pre><pre>&lt;div&gt; {{ user.name }} &lt;/div&gt;</pre><pre>&lt;div&gt; &lt;a :href=’”mailto:”+user.email’&gt;{{ user.email }}&lt;/a&gt; &lt;/div&gt;</pre><pre>&lt;div&gt; {{ user.phone }} &lt;/div&gt;</pre><pre>&lt;div&gt; {{ user.website }} &lt;/div&gt;</pre><pre>&lt;span v-on:click=”removeUser(index)” class=”link”&gt;delete&lt;/span&gt;</pre><pre>&lt;/div&gt;</pre><p><strong><em>Use of getters</em></strong></p><pre><strong><br></strong>&lt;p&gt;Total users in store : &lt;strong&gt;{{this.totalUsers}}&lt;/strong&gt;&lt;/p&gt;</pre><p>we had mapGetters in our application.simply call that getter function.</p><p><strong><em>Manipulations of store</em></strong></p><p>Removing an user from store</p><pre>removeUser(id){</pre><pre>this.REMOVE_USER(id)</pre><pre>},</pre><p>Adding an user to the store</p><pre>&lt;button v-on:click=&quot;addUserInput&quot;&gt;Add&lt;/button&gt;</pre><pre>addUserInput(){</pre><pre>this.addUser([{<br>    “id”: this.maxId, // again a getter function<br>    “name”: this.username,<br>    “phone”:this.phone,<br>    “email”:this.email,<br>    “website”:this.website,<br>}])<br>this.username = &#39;&#39;<br>this.phone = &#39;&#39;<br>this.email = &#39;&#39;<br>this.website = &#39;&#39;<br>},</pre><pre>addUser:function(data){<br>  this.ADD_USER(data)<br>}</pre><p><strong><em>Finally lets go through the steps once again</em></strong></p><ol><li>Initialize store with respective getters,mutations and state</li><li>On load of the component call the API,on success of it store the data in our vuex store by passing the data to a mutation function.Use mapMutations to call mutation function from a component</li><li>Use getters wherever necessary.</li><li>Implement the same for ADD and DELETE functionality.</li><li>Bind store variables to components using mapState.</li></ol><p><strong><em>Screenshot</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*X5hOMjFvgGFL_vd2P8sU_Q.png" /></figure><blockquote>The complete example can be found here<br><a href="https://github.com/ubercooluk/vuex-example">https://github.com/ubercooluk/vuex-example</a></blockquote><p>just clone the repo. Then all you have to do is</p><pre> yarn install<br> yarn serve</pre><p><strong>Conclusion<br></strong>We have gone through vuex store,helper functions in store and finally how to communicate between store and components and use a single ,manageable source of data for our application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=351a0b2deaea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating reusable HTML styled components with react-jss]]></title>
            <link>https://unnikrishnand.medium.com/creating-reusable-html-styled-components-with-react-jss-2c56caa9e97e?source=rss-3cae0508dd70------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c56caa9e97e</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Unni Krishnan D]]></dc:creator>
            <pubDate>Sat, 21 Jul 2018 15:51:56 GMT</pubDate>
            <atom:updated>2018-07-21T16:01:13.775Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the biggest challenges developers face while developing a web application is how to efficiently manage CSS.Traditional CSS can generate a lot of dead code in our application and thereby impacting the performance as well as size of our bundle.</p><p>Traditional CSS is all about static files which contains key(CSS property) and values.In normal scenarios we will be loading a lot of unwanted CSS in our application.Imagine a scenario where we can write CSS in JavaScript as objects or components and the unlimited possibilities to harness the power of JavaScript.</p><p><strong>Lets Dig in :-)</strong></p><h4><strong>Prerequisites</strong></h4><p>A basic understanding of <strong>ReactJS</strong>,states,props ,higher order components and most importantly manipulation of JavaScript objects.</p><h4><strong>Installation</strong></h4><blockquote>we will be using Facebook’s <strong>create-react-app</strong> in this tutorial and <strong>yarn </strong>as package manager along with the package <a href="https://github.com/cssinjs/react-jss"><strong>react-jss</strong></a></blockquote><h4><strong>Bootstrapping</strong></h4><p>yarn create react-app demoapp_reactjss</p><h4>Installing react-jss</h4><p>cd demoapp_reactjss <br>yarn add react-jss</p><p>Once bootstrapping and installation is done we can create our project structure.<strong>I&#39;m creating a contact-us page with theming support</strong>.Create files as per the screenshot.We will go through each files in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*cTZT5qMtJF8O_rgjHoqj5A.png" /></figure><p>Files</p><p><strong>App.js</strong> :: Our Main component file where we will be loading all our sub components.<br><strong>Reusables/inputs.js</strong> ::Our main goal was the make it reusable as much as possible.For a contact-us page we require components like Inputs,Buttons ,labels etc.</p><pre>import React, { Component } from ‘react’;<br>class Input extends Component {<br> render() {<br> return (<br> &lt;div className=”Input”&gt;<br> &lt;input type=”text” placeholder={this.props.placeholder} className={this.props.classes.myInput} /&gt;<br> &lt;/div&gt;<br> );<br> }<br>}<br>class TextArea extends Component {<br> render() {<br> return (<br> &lt;div className=”TextArea”&gt;<br> &lt;textarea placeholder={this.props.placeholder} className={this.props.classes.myTextarea}&gt;&lt;/textarea&gt;<br> &lt;/div&gt;<br> );<br> }<br>}<br>class Layout extends Component {<br> render() {<br> return (<br> &lt;div className={this.props.classes.layout}&gt;<br> {this.props.children}<br> &lt;/div&gt;<br> )<br> }<br>}<br>class Button extends Component {<br> render() {<br> return (<br> &lt;div className={this.props.classes.btnContainer} onClick={this.props.clickEvent}&gt;<br> &lt;button className={this.props.classes.btn}&gt;<br> {this.props.children}<br> &lt;/button&gt;<br> &lt;/div&gt;<br> );<br> }<br>}<br>class Label extends Component {<br> render() {<br> return (<br> &lt;div className={this.props.classes.parentDiv}&gt;<br> &lt;label className={this.props.classes.lbl}&gt;{this.props.children}&lt;/label&gt;<br> &lt;/div&gt;<br> )<br> }<br>}</pre><pre>const Reusables = {<br> Button :Button ,<br> TextArea : TextArea ,<br> Input : Input,<br> Layout : Layout,<br> Label : Label<br>};</pre><pre>export default Reusables;</pre><p>So we have created <strong>5 </strong>reusable components(Button,Label,Input,TextArea,Layout). We already have various props injected in these components.</p><p><strong>colors.js</strong></p><p>We are storing colors as an object.<strong>This is not CSS.</strong></p><pre>const colors = {<br>  default : {<br>    buttoncolor : &quot;#581845&quot;,<br>    bordercolor :&quot;#e2aea3&quot;,<br>    bgcolor:&quot;#DAF7A6&quot;<br>  },<br>  dark : {<br>    buttoncolor : &quot;#001243&quot;,<br>    bordercolor :&quot;#581845&quot;,<br>    bgcolor:&quot;#C70039&quot;<br>  }<br>};<br>export default colors;</pre><p><strong>default.js</strong></p><p>Here also we are using one JavaScript object.We have different sections like button,input ,layout etc.</p><pre>import colors from &#39;./colors.js&#39;;<br>const defaulttheme  = {<br>     button : {<br>       buttonDefaultColor : colors.dark.buttoncolor,<br>       bordercolor : colors.dark.bordercolor,<br>       fontWeight : &quot;bold&quot;,<br>       borderWidth :&quot;1px&quot;,<br>       borderStyle : &quot;solid&quot;,<br>       width : &quot;120px&quot;,<br>       fontFamily :&quot;Calibri&quot;<br>     },<br>     input : {<br>       buttonDefaultColor : colors.dark.buttoncolor,<br>       bordercolor : colors.dark.bordercolor,<br>       fontWeight : &quot;bold&quot;,<br>       borderWidth :&quot;1px&quot;,<br>       borderStyle : &quot;solid&quot;,<br>       width : &quot;120px&quot;<br>     },<br>     textarea : {<br>       buttonDefaultColor : colors.dark.buttoncolor,<br>       bordercolor : colors.dark.bordercolor,<br>       fontWeight : &quot;bold&quot;,<br>       borderWidth :&quot;1px&quot;,<br>       borderStyle : &quot;solid&quot;,<br>       width : &quot;150px&quot;<br>     },<br>     label : {<br>       buttonDefaultColor : colors.dark.buttoncolor,<br>       bordercolor : colors.dark.bordercolor,<br>       fontWeight : &quot;bold&quot;,<br>       width : &quot;120px&quot;,<br>       minWidth:&quot;120px&quot;,<br>       fontFamily :&quot;Calibri&quot;<br>     },<br>     layout : {<br>       bgcolor : colors.dark.bgcolor<br>     }</pre><pre>};<br>export default defaulttheme;</pre><h4><strong>dark.js</strong></h4><p>The same file as default.js.But with different values</p><pre>import colors from &#39;./colors.js&#39;;<br>const darktheme= {<br>     button : {<br>       buttonDefaultColor : colors.dark.buttoncolor,<br>       bordercolor : colors.dark.bordercolor,<br>       fontWeight : &quot;bold&quot;,<br>       borderWidth :&quot;1px&quot;,<br>       borderStyle : &quot;solid&quot;,<br>       width : &quot;120px&quot;,<br>       fontFamily :&quot;Calibri&quot;<br>     },<br>     input : {<br>       buttonDefaultColor : colors.dark.buttoncolor,<br>       bordercolor : colors.dark.bordercolor,<br>       fontWeight : &quot;bold&quot;,<br>       borderWidth :&quot;1px&quot;,<br>       borderStyle : &quot;solid&quot;,<br>       width : &quot;120px&quot;<br>     },<br>     textarea : {<br>       buttonDefaultColor : colors.dark.buttoncolor,<br>       bordercolor : colors.dark.bordercolor,<br>       fontWeight : &quot;bold&quot;,<br>       borderWidth :&quot;1px&quot;,<br>       borderStyle : &quot;solid&quot;,<br>       width : &quot;150px&quot;<br>     },<br>     label : {<br>       buttonDefaultColor : colors.dark.buttoncolor,<br>       bordercolor : colors.dark.bordercolor,<br>       fontWeight : &quot;bold&quot;,<br>       width : &quot;120px&quot;,<br>       minWidth:&quot;120px&quot;,<br>       fontFamily :&quot;Calibri&quot;<br>     },<br>     layout : {<br>       bgcolor : colors.dark.bgcolor<br>     }</pre><pre>};<br>export default darktheme;</pre><p>Next we need to create the JSS components.For better modularity i have created one JSS file for each components.A JSS component is a ReactJS component where we can pass values as props from the parent component as well as values from the theme file.</p><p><strong>button.js</strong><br>Here btn is the className we are using in our reusable component.The values are from theme(theme.button.FontFamily) as well as props(props.borderRadius).</p><pre>const Buttonstyles = theme =&gt; ({</pre><pre>btn: props =&gt; ({<br>      color: theme.button.buttonDefaultColor,<br>      border : theme.button.borderWidth+&quot; &quot;+ theme.button.borderStyle+&quot; &quot;+theme.button.bordercolor,<br>      width : theme.button.width,<br>      fontWeight : theme.button.fontWeight,<br>      borderRadius : props.borderRadius +&quot;px&quot;,<br>      fontFamily:theme.button.fontFamily<br>    })</pre><pre>});<br>export default Buttonstyles;</pre><p>Other JSS files are attached at the end of the article.</p><p>Now Integrating everything in our App.js</p><pre>import React, { Component } from &#39;react&#39;;<br>import injectSheet, {ThemeProvider} from &#39;react-jss&#39;;<br>//reusable components<br>import Reusables from &#39;./reusables/inputs&#39;;<br>//styles<br>import Buttonstyles from &#39;./styles/button.js&#39;;<br>import InputStyles from &#39;./styles/input.js&#39;;<br>import TextAreaStyles from &#39;./styles/textarea.js&#39;;<br>import LayoutStyles from &#39;./styles/layout.js&#39;;<br>import LabelStyles from &#39;./styles/label.js&#39;;<br>//themes<br>import defaulttheme from &#39;./styles/themes/default.js&#39;;<br>import darktheme from &#39;./styles/themes/dark.js&#39;;<br>class App extends Component {<br>  constructor() {<br>    super();<br>    //set up a theme state ,defaulttheme<br>    this.state = {<br>      theme : defaulttheme,<br>      statusmsg : &quot;&quot;<br>    }<br>  }<br>  changeTheme(t)  {<br>    //this function will toggle the theme<br>    this.setState({<br>      theme : (t == &quot;dark&quot;) ? darktheme : defaulttheme<br>    })<br>  }<br>  clickContact() {<br>    //just a function for the click<br>    this.setState ({<br>      statusmsg :&quot;Hello thanks for contacting us !,We will get back to you&quot;<br>    })</pre><pre>console.log(&quot;Click&quot;);<br>  }<br>  render() {</pre><pre>//each of these inject methods creates reusable elements from the Reusables and injects with the style from theme<br>      const Input =  injectSheet(InputStyles)(Reusables.Input);<br>      const StyledButton = injectSheet(Buttonstyles)(Reusables.Button);<br>      const TextArea = injectSheet(TextAreaStyles)(Reusables.TextArea);<br>      const LayoutComponent = injectSheet(LayoutStyles)(Reusables.Layout);<br>      const Label = injectSheet(LabelStyles)(Reusables.Label)</pre><pre>return (<br>      &lt;div className=&quot;App&quot;&gt;<br>      Change theme &lt;button onClick={this.changeTheme.bind(this,&#39;dark&#39;)}&gt;Dark&lt;/button&gt;<br>      &lt;button onClick={this.changeTheme.bind(this,&#39;light&#39;)}&gt;Light&lt;/button&gt;<br>      &lt;ThemeProvider theme={this.state.theme}&gt;<br>            &lt;div&gt;</pre><pre>&lt;LayoutComponent direction=&quot;column&quot; justify=&quot;flex-start&quot; &gt;</pre><pre>&lt;LayoutComponent direction=&quot;row&quot; justify=&quot;flex-start&quot;&gt;<br>                           &lt;Label&gt;Name&lt;/Label&gt;<br>                            &lt;Input borderRadius=&quot;5&quot; /&gt;<br>                    &lt;/LayoutComponent&gt;</pre><pre>&lt;LayoutComponent direction=&quot;row&quot; justify=&quot;flex-start&quot;&gt;<br>                             &lt;Label&gt;Email&lt;/Label&gt;<br>                              &lt;Input borderRadius=&quot;5&quot; /&gt;<br>                    &lt;/LayoutComponent&gt;</pre><pre>&lt;LayoutComponent direction=&quot;row&quot; justify=&quot;flex-start&quot;&gt;<br>                              &lt;Label&gt;Address&lt;/Label&gt;<br>                              &lt;TextArea borderRadius=&quot;5&quot; /&gt;<br>                    &lt;/LayoutComponent&gt;</pre><pre>&lt;/LayoutComponent&gt;</pre><pre>&lt;StyledButton borderRadius=&quot;5&quot; clickEvent={this.clickContact.bind(this)}&gt;Contact Us&lt;/StyledButton&gt;<br>&lt;p&gt;{this.state.statusmsg}&lt;/p&gt;<br>              &lt;/div&gt;<br>            &lt;/ThemeProvider&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default App;</pre><p><strong>Explanation of App.js (How it works)</strong></p><blockquote>const Input = injectSheet(InputStyles)(Reusables.Input);</blockquote><p>This creates a Input Component from the reusables/inputs.js</p><blockquote>&lt;ThemeProvider theme={this.state.theme}&gt;</blockquote><p>This creates a container for theming with theme set to state.theme</p><pre>&lt;LayoutComponent direction=&quot;row&quot; justify=&quot;flex-start&quot;&gt;<br>       &lt;Label&gt;Name&lt;/Label&gt;<br>        &lt;Input borderRadius=&quot;5&quot; /&gt;<br> &lt;/LayoutComponent&gt;</pre><p>Here the props direction,justify are accessible in the corresponding JSS file (style/layout.js). The Label and Input are rendered inside the Layout Component from reusables/inputs.js.</p><pre>class Layout extends Component {<br>  render() {<br>    return (<br>      &lt;div className={this.props.classes.layout}&gt;<br>         {this.props.children}//here we get the Label and Input<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><p>And finally we have a state toggler for theme</p><pre>changeTheme(t)  {<br>    //this function will toggle the theme<br>    this.setState({<br>      theme : (t == &quot;dark&quot;) ? darktheme : defaulttheme<br>    })<br>  }</pre><h3><strong>Dark theme</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_zUV6d3tZkxAdHtiXZszg.png" /></figure><h3><strong>Default theme (Light)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awniuicirnbBXtDWMXiPaQ.png" /></figure><h3>Conclusion</h3><p>As you can see we can only include the JSS files needed for a component there by reducing the size of bundle and dead CSS code.DOM Manipulations w.r to CSS(Like Jquery ) also can be achieved easily.</p><p><strong>Source files</strong></p><p><a href="https://drive.google.com/file/d/19ygLU-zeieuYlm-VZnmXODrzOHfhPir9/view?usp=sharing"><strong>Download</strong></a></p><p>Extract</p><p>run<br>yarn install</p><p>yarn start</p><p>navigate to localhost:3000/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c56caa9e97e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring code coverage with Karma ,jasmine and Angular 2]]></title>
            <link>https://unnikrishnand.medium.com/configuring-code-coverage-with-karma-jasmine-and-angular-2-7b9a325cbb1e?source=rss-3cae0508dd70------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b9a325cbb1e</guid>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Unni Krishnan D]]></dc:creator>
            <pubDate>Sun, 09 Apr 2017 10:49:34 GMT</pubDate>
            <atom:updated>2017-04-09T10:49:57.636Z</atom:updated>
            <content:encoded><![CDATA[<p>What is code coverage ?</p><p>As the good ol google says “In computer science, code coverage is a measure used to describe the degree to which the source code of a program is executed when a particular test suite runs.” ,simple as it is ;)</p><p>How do we do it ?</p><p><strong>Ingredients</strong><br>1.Basic knowledge of Angular 2<br>2,Typescript (if you are coding in type script)<br>3.Npm<br>4.Karma Jasmine</p><p>and finally some good googling skills ;)</p><p>Step 1 : Scaffold your Angular 2 Application ,Install all the necessary packages that comes along with the package.json<br>In a npm console ,</p><h4>ng new covereageexample</h4><p>Navigate inside the folder and do</p><h4>npm install</h4><p>finally after installation ,check the application is running by</p><h4>ng serve</h4><p>Now lets configure the ingredients needed for code coverage<br><strong>1.karma typescript</strong><br>Run unit tests written in Typescript with full type checking, seamlessly without extra build steps or scripts.<br>https://www.npmjs.com/package/karma-typescript</p><p><strong>2.karma-typescript-angular-transform</strong><br>This plugin rewrites relative urls in the templateUrl and styleUrls properties of Angular2 components, making sure that the Angular framework can resolve the urls when running tests with karma-typescript<br><a href="https://www.npmjs.com/package/karma-typescript-angular2-transform">https://www.npmjs.com/package/karma-typescript-angular2-transform</a><br><strong>3.karma-html-reporter</strong><br>This plugin will generates a HTML report of all the test cases in the application<br><a href="https://www.npmjs.com/package/karma-html-reporter">https://www.npmjs.com/package/karma-html-reporter</a></p><p>Add these packages in your package.json and do npm install (I will share the entire code at the end of this blog ;))</p><p>The karma.config file</p><h4>module.exports = function(config) {<br> config.set({<br> //import the frameworks<br> frameworks: [“jasmine”, “karma-typescript”],<br> //base.spec.ts is the file which bootstraps the testing<br> //sr/app … will contain our code<br> files: [<br> { pattern: “base.spec.ts” },<br> { pattern: “src/app/**/*.+(ts|html)” }<br> ],<br> //preprocessor will allow us to do some work before serving it to the //browser<br>//<a href="http://karma-runner.github.io/1.0/config/preprocessors.html">http://karma-runner.github.io/1.0/config/preprocessors.html</a><br> preprocessors: {<br> “**/*.ts”: [“karma-typescript”]<br> },<br> <br> karmaTypescriptConfig: {<br> bundlerOptions: {<br> entrypoints: /\.spec\.ts$/,<br>//transform plugin for relative urls (styleUrl and tetmplateUrl) <br> transforms: [<br> require(“karma-typescript-angular2-transform”)<br> ]<br> },<br>//coverage reports will be generated in the `coverage` folder on the root level <br> coverageOptions: {<br> instrumentation: true,<br> <br> }<br> },<br>//generation of HTML reports<br> htmlReporter: { <br>//directory ,report will get generated inside folder `testcases` in the root folder<br> outputDir: ‘testcases’,<br> <br> },<br> //progress — for running the test case<br> //karma-type-script — for code coverage<br> //html — generation of HTML reports of test cases<br> reporters: [“progress”, “karma-typescript”,”html”],<br> <br> browsers: [“Chrome”]<br> });<br>};</h4><p>This is my Hellocomponent.ts look like</p><h4>import { Component } from “<a href="http://twitter.com/angular/core">@angular/core</a>”;</h4><h4><a href="http://twitter.com/Component">@Component</a>({<br> selector: “app-hello”,<br> styleUrls: [“../assets/style/main.css”],<br> templateUrl: “hello.html”<br>})<br>export class HelloComponent {<br> public title = “Hello :)”;<br> <br>}</h4><p>And my hellocomponent.spec.ts will look like this</p><h4>import { DebugElement } from “<a href="http://twitter.com/angular/core">@angular/core</a>”;<br>import { async, ComponentFixture, TestBed } from “<a href="http://twitter.com/angular/core">@angular/core</a>/testing”;<br>import { By } from “<a href="http://twitter.com/angular/platform-browser">@angular/platform-browser</a>”;</h4><h4>import { HelloComponent } from “./hello”;</h4><h4>describe(“HelloComponent”, () =&gt; {</h4><h4>let fixture: ComponentFixture&lt;HelloComponent&gt;;</h4><h4>beforeEach(async(() =&gt; {</h4><h4>return TestBed<br> .configureTestingModule({<br> declarations: [HelloComponent]<br> })<br> .compileComponents()<br> .then(() =&gt; {<br> fixture = TestBed.createComponent(HelloComponent);<br> });<br> }));</h4><h4>it(“should display original title”, () =&gt; {<br> let debugElement = fixture.debugElement.query(By.css(“h1”));<br> fixture.detectChanges();<br> expect(debugElement.nativeElement.textContent).toEqual(“Hello :)”);<br> });</h4><h4>it(“should display a different test title”, () =&gt; {<br> let debugElement = fixture.debugElement.query(By.css(“h1”));<br> fixture.componentInstance.title = “Test Title”;<br> fixture.detectChanges();<br> expect(debugElement.nativeElement.textContent).toEqual(“Test Title”);<br> });<br>});</h4><p>And my hello.html</p><h4>&lt;h1&gt;{{title}}&lt;/h1&gt;</h4><p>So we have two test cases written which covers all the functionality in hellocomponent ,<br>The coverage report will look like above ,its 100% covered<br>Report can be found under</p><p><strong>coverage/ &lt;yourbrowser_name+version&gt;/index.html</strong></p><p>Clicking on hello.ts link in the index.html will show our code ,what is covered and not covered</p><p>Now lets check our coverage functionality really works or not add some code in Hello.ts</p><p>import { Component } from “<a href="http://twitter.com/angular/core">@angular/core</a>”;</p><p><a href="http://twitter.com/Component">@Component</a>({<br> selector: “app-hello”,<br> styleUrls: [“../assets/style/main.css”],<br> templateUrl: “hello.html”<br>})<br>export class HelloComponent {<br> public title = “Hello :)”;<br> //i have added this piece of code and no test cases written yet,<br> foo() {<br> return ‘bar’;<br> }<br>}</p><p>Lets generate a code covereage again by running npm test, and see the coverage is now only 88.89% (open the inde.html file in the coverage folder)</p><p>If we click on the hello.ts file we can see the test cases for the function `foo` is not written ,so we have to write test cases for foo function. An ideal code coverage for any project will be around 75 to 80%</p><p>So that’s it guys , ill be covering more on the jasmine test cases in my next post</p><p>You can find the entire files and code in the below link</p><p><a href="https://www.dropbox.com/s/bao8rgqjj6iefjw/angular2.zip?dl=0">https://www.dropbox.com/s/bao8rgqjj6iefjw/angular2.zip?dl=0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b9a325cbb1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AngularJS 2 $http testing with Jasmine]]></title>
            <link>https://unnikrishnand.medium.com/angularjs-2-http-testing-with-jasmine-c34ae3b7c8e7?source=rss-3cae0508dd70------2</link>
            <guid isPermaLink="false">https://medium.com/p/c34ae3b7c8e7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular2]]></category>
            <dc:creator><![CDATA[Unni Krishnan D]]></dc:creator>
            <pubDate>Sun, 09 Apr 2017 10:40:07 GMT</pubDate>
            <atom:updated>2017-04-09T10:40:07.577Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>AngularJS 2 $http testing with Jasmine</strong></p><p>Prerequisites <br>1.Basic knowledge of AngularJS 2 ,Jasmine<br>2.Understanding of “What is $http call ” ,basically how an API call works</p><p>First lets configure our component</p><h4>import { Component } from ‘<a href="http://twitter.com/angular/core">@angular/core</a>’;<br>import { Http, Response } from ‘<a href="http://twitter.com/angular/http">@angular/http</a>’;</h4><h4>//including dependencies for catch and map<br>import ‘rxjs/add/operator/catch’;<br>import ‘rxjs/add/operator/map’;<br><a href="http://twitter.com/Component">@Component</a>({<br> selector: ‘app-root’,<br> templateUrl: ‘./app.component.html’,<br> styleUrls: [‘./app.component.css’]<br>})<br>export class AppComponent {<br> public ajaxdata;<br> constructor (private http: Http) {<br> this.ajaxdata = {}; //a simple variable to bind API data to HTML<br> }<br> <br> <br> callApi() {<br> return this.http.get(‘<a href="https://jsonplaceholder.typicode.com/posts/1&#39;">https://jsonplaceholder.typicode.com/posts/1&#39;</a>)<br> .map(res =&gt; res.json()); //return as JSON<br> }<br> <br> fetchApi() { //function for subscribing the data<br> this.callApi() <br> .subscribe(<br> data =&gt; this.handleData(data),<br> err =&gt; this.handleError(err),<br> <br> ); <br> }<br> <br> handleData(data){<br> console.log(data);<br> this.ajaxdata = data.body; //ajaxdata , variable to hold the API repsonseand binding it o the html</h4><h4>console.log(this.ajaxdata);</h4><h4>}<br> handleError(data){<br> console.log(data);<br> }<br>}</h4><p>Lets see out HTML</p><h4>&lt;button (click)=”fetchApi()”&gt;Call API &lt;/button&gt;<br>&lt;div&gt;Server response&lt;/div&gt;<br>&lt;div id =”titledata”&gt;{{ajaxdata}}&lt;/div&gt;</h4><p>So the functionality is simple and clean on click of the “Call API ” button , we will get the response :)</p><p><strong>Testing this $http call using Jasmine</strong></p><p>In our appcomponent.spec.ts ,include all the required libraries</p><h4>import { TestBed, async, inject } from ‘<a href="http://twitter.com/angular/core">@angular/core</a>/testing’;<br>import {<br> HttpModule,<br> Http,<br> Response,<br> ResponseOptions,<br> XHRBackend<br>} from ‘<a href="http://twitter.com/angular/http">@angular/http</a>’;<br>import { MockBackend } from ‘<a href="http://twitter.com/angular/http">@angular/http</a>/testing’;</h4><h4>import { AppComponent } from ‘./app.component’;</h4><p>Now we have to configure our TestBed ,we use <strong>MockBackend </strong>for testing $http calls</p><p>The beforeEach section ,we have to include <strong>MockBackend</strong></p><h4>beforeEach(async(() =&gt; {<br> TestBed.configureTestingModule({<br> imports: [HttpModule],</h4><h4>declarations: [<br> AppComponent<br> ],<br> providers:[<br> AppComponent,<br> { provide: XHRBackend, useClass: MockBackend },<br>],<br> }).compileComponents();</h4><h4>}));</h4><p>Now lets write our test case</p><h4>it(‘should return a mock API’,<br> inject([AppComponent, XHRBackend], (app, xhr) =&gt; {</h4><h4>const mockResponse = {<br> body:”body from mock”<br> };</h4><h4>xhr.connections.subscribe((connection) =&gt; {<br> connection.mockRespond(new Response(new ResponseOptions({<br> body:JSON.stringify(mockResponse)<br> })));<br> });</h4><h4>app.callApi().subscribe((response) =&gt; {<br> expect(response).toEqual(<br> {<br> body:”body from mock”<br> }<br> );<br> //call the handle function in component ,check for the console.log() messages inside the handleData function<br> app.handleData({<br> body:”body from mock”<br> }); <br> });</h4><h4>}));</h4><p>So thats it ,We have tested our <strong>$http</strong> calls using <strong>MockData</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c34ae3b7c8e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>