<?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 Muthu Kumaran on Medium]]></title>
        <description><![CDATA[Stories by Muthu Kumaran on Medium]]></description>
        <link>https://medium.com/@muthukumarana?source=rss-8becd093b18------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wycbMFUofdTBbNi1Zgdddw.jpeg</url>
            <title>Stories by Muthu Kumaran on Medium</title>
            <link>https://medium.com/@muthukumarana?source=rss-8becd093b18------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:39:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muthukumarana/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[Next.Js - Assets, Metadata, Scripts, Styles]]></title>
            <link>https://medium.com/@muthukumarana/next-js-assets-metadata-scripts-styles-8621fc15d2bf?source=rss-8becd093b18------2</link>
            <guid isPermaLink="false">https://medium.com/p/8621fc15d2bf</guid>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs-13]]></category>
            <dc:creator><![CDATA[Muthu Kumaran]]></dc:creator>
            <pubDate>Thu, 04 May 2023 03:41:43 GMT</pubDate>
            <atom:updated>2023-05-04T03:41:43.347Z</atom:updated>
            <content:encoded><![CDATA[<p>Next.js features apart from the basic ones, with poc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*kWpxWi9aOQVCtzh_LObRTQ.png" /></figure><p>If you are new to Next.js, please checkout below story to know the basic and key features of Next.js</p><p><a href="https://medium.com/@muthukumarana/next-js-most-recommended-react-js-framework-why-7922b7f27bc7">Next.Js - most recommended React Js framework. Why ?</a></p><p>In this story, we will see some of the non core features, but are must to know while working with Next.js</p><h3>1. Assets - Images</h3><ul><li>All static assets like images are to be placed in <strong><em>public</em></strong> directory</li><li>Next.js has a <strong><em>Image</em></strong> component of its own, which makes your image responsive, optimize it, and lazy load when it enters view port.</li></ul><p>Its time to test this <em>Image</em> component, lets create a new page “profile” to render an image using <em>Image</em> component and <em>img</em> tag</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*vcvA9uZ9cQHQDpmm.png" /></figure><p>In above code, we have:</p><ul><li>Added an image my_pic.jpg in “public/images” and used its path in Next.js <em>Image </em>component and <em>img tag </em>(all red arrows in above image)</li><li>And you can see a bunch of <em>br</em> tags, to hide the images from view port on load.</li></ul><p>On page load we can see only the header and one image downloaded, this is done by the <em>img </em>tag ( as it cant lazy load)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*yH033WkMjZ65Vk2d.png" /><figcaption>img tag downloaded image even if its not in view port</figcaption></figure><p>As we scroll down, the <em>Image </em>component gets into the view port and <strong>downloads the image lazily</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*phq-hEixyQDIIh8_.png" /><figcaption>Image component lazy loads the image</figcaption></figure><p>Also you can see the image url for the Image component having responsive parameters in them:<br>Web : <a href="http://localhost:3000/_next/image?url=%2Fimages%2Fmy_pic.jpg&amp;w=640&amp;q=75">/_next/image?url=%2Fimages%2Fmy_pic.jpg&amp;<strong>w=640&amp;q=75</strong></a><strong><br></strong>Mobile : <a href="http://localhost:3000/_next/image?url=%2Fimages%2Fmy_pic.jpg&amp;w=1080&amp;q=75">/_next/image?url=%2Fimages%2Fmy_pic.jpg&amp;<strong>w=1080&amp;q=75</strong></a></p><p>Thus <strong>responsiveness handled too</strong>.</p><h3>2. Metadata (Head)</h3><p>To add metadata like title for a page, we can use <em>Head</em> component of Next.js. This can be done in few simple steps:</p><ul><li>Import the Head component, and add it in the page components, with a title tag inside it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_fxqfpXWRUz1H6GEVZaFkg.png" /></figure><p>And the same will get rendered in browser for the corresponding pages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNUhWVuxfpT3vG_aSbZhlA.png" /><figcaption>Page titles getting rendered by the Head compoent as expected</figcaption></figure><p>Not just <em>title</em>, we can add all head related tags like <em>style</em>, <em>link</em>, <em>script</em> etc like wise.</p><h3>3. Third party scripts:</h3><p>Adding 3rd party scripts might get tricky using regular <em>script</em> tag inside <em>Head</em> component. And some scripts has to loaded before or after or only on certain event etc.</p><p>To solve this Next.js comes with its own <em>Script</em> component. Lets see it on action.</p><ul><li>Import the <em>Script</em> component, and add it in the page component, with a src attribute holding the path/cdn of required library.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*plgL_0QTG2Hv9BLKpOSHpA.png" /><figcaption>Script component pointed by red arrows. Blue ones are for the 3rd party.</figcaption></figure><p>In above code, we can see:</p><ul><li>Script tag loads the anime js, and we have given the strategy to load as “beforeInteractive”.</li><li>This strategy will make sure the library is loaded well in advance</li><li>And in useEffect, we use the anime libray to spin a text as shown below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*P86dbsXEB92aataDDuKuQg.gif" /><figcaption>Animation script loaded by Script component, spins the text</figcaption></figure><p>Just like “beforeInteractive”, we have other strategies as well like “afterInteractive”, “lazyOnload”, and “worker”.</p><p>Thus providing us with option to control the script loading easily.</p><p>Also we have a <em>onLoad </em>property that take a function to be executed on load of the library (we can use that to trigger our animation rather than useEffect)</p><h3>4. Styles</h3><p>Next.js allows us to add styles through css modules, where our style sheets names should be {some_name}.module.css. Lets try that</p><ul><li>Lets create a css module, cssstyles.module.css</li></ul><pre>.cssText {<br>    color: red;<br>    font-size: 30px;<br>    padding: 50px;<br>}</pre><ul><li>Creates a page and import the css module</li></ul><pre>import cssStyles from &#39;./cssstyles.module.css&#39;;</pre><ul><li>Now lets use the imported style in our jsx and assign a class to a className attribute</li></ul><pre>&lt;div className={cssStyles.cssText}&gt;<br>    Css styled text<br>&lt;/div&gt;</pre><p>That&#39;s all, Next.js will use the css style without any further change. Lets try for other types scss and sass types as shown bleow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yelB5MWbpzQXLrKdN4kUmQ.png" /><figcaption>Imported css, scss and sass module files and used the corresponding styles</figcaption></figure><p>And while rendering the page, we can see all type styles applied to the corresponding divs as expected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRPaTrOCnUPnk_ou2bh3jA.png" /><figcaption>Next.js rendering UI with css and sass with inbuilt support</figcaption></figure><p>Not just css and scss, Next.js can also support PostCSS libraries, styled compoents and other css-in-js types as well.</p><p>For adding global styles, that can be used in all pages, we have to add it in “/pages/_app.js”</p><pre>// `pages/_app.js`<br>import &#39;../styles/global.css&#39;;</pre><p>Thus handling stlyes is more easier than ever.</p><h3>Conclusion:</h3><ul><li>Static content like images are made responsive, lazy loaded and optimized using the <em>Image</em> component.</li><li>Add metadata like title to the page using <em>Head</em> component.</li><li>Control the way the script loads with <em>Script </em>component using different strategies and know when a script is loaded.</li><li>Css, Sass and many more ways of adding styles to our app can be done with just css module and Next.js in built support.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8621fc15d2bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.Js - most recommended React Js framework. Why ?]]></title>
            <link>https://medium.com/@muthukumarana/next-js-most-recommended-react-js-framework-why-7922b7f27bc7?source=rss-8becd093b18------2</link>
            <guid isPermaLink="false">https://medium.com/p/7922b7f27bc7</guid>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Muthu Kumaran]]></dc:creator>
            <pubDate>Thu, 04 May 2023 03:21:27 GMT</pubDate>
            <atom:updated>2023-05-04T03:43:03.601Z</atom:updated>
            <content:encoded><![CDATA[<h3>Next.Js - most recommended React Js framework. Why ?</h3><p>Next.js basics and its key concepts with poc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*KQQmZ63rrcfQyhgB7UWEyw.png" /></figure><h3><strong>What’s Next.Js:</strong></h3><ul><li>Next Js is a <strong><em>React framework</em></strong>, it comes with its own building blocks to create a web application.</li><li>It provides a <strong>structure</strong> to our application</li><li>For <strong>improved local development experience</strong> it comes with features like Typescript, ESLint, fast refresh etc</li><li>In <strong>production</strong> mode it transforms the code to be <strong>performant</strong> and <strong>accessible</strong></li><li>Next.Js has <strong>its own compiler</strong> written in Rust, that is used for compilation, minification, bundling, and more for application to go production.</li><li>It supports all types of rendering, <strong>Server-Side Rendering, Static Site Generation, </strong>and<strong> Client-Side Rendering </strong>and<strong> </strong>it can be chosen at page level</li></ul><h4><strong>Create a simple Next Js app:</strong></h4><p>To explore some of the key features of Next.Js. Lest create a basic app from scratch.</p><pre>npx create-next-app@latest</pre><p>While doing create-next-app, we will be given with following options to choose (we gave the project name as “nextjs-app”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*UFV8qJdAbAnpiWSYGZxATA.png" /></figure><p>After this, it will install a set of node modules for our react app. Once the project is created, we can start running the app by navigating to the app directory and do “npm run dev”</p><pre>cd nextjs-app<br><br>npm run dev</pre><p>The app gets started in dev mode on localhost:3000 as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WfchMJqNKFu3AMKNoFEHMQ.png" /></figure><h3>Lets explore some basic key feature one by one</h3><h4><strong>1. Pages (routes):</strong></h4><ul><li>In Next js, pages are nothing but React component in the “pages” folder.</li><li>It follows a <strong>file system based routing</strong>, for example:<br>- “page/index.tsx” represents <em>“/”</em> route<br>- “page/first.tsx” represents <em>“/first”</em> route<br>- “page/login/signin.tsx” represents <em>“/login/signin”</em> route</li><li>So to create a new page, just add a jsx file (react component) inside “pages” folder in a path according to the required route.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JEL_hpm2bPgvFAeFxYMCCA.png" /><figcaption>page created with path “pages/logn/signin.tsx” getting rendered as “/login/signin” in browser</figcaption></figure><h4><strong>2. Client side navigation:</strong></h4><ul><li>This can be done using the <em>Link</em> component of Next.Js, where we pass the route to <em>href</em> property</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*G_FNpBQ99ZiJxQGxjNcmYg.png" /><figcaption>sign in component with “Link” to “/first” page</figcaption></figure><p>Link component simply does a client side rendering. Only the js for the page is fetched not the entire dom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*2yZ01cUFt-6C0WBJ4SkqcA.png" /><figcaption>network tab while navigating via Link compoent</figcaption></figure><p>Where as a regular anchor tag will fetch the entire page from the server and reloads the whole page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*kQlHaucKek5m7yBBXJ3cqw.png" /><figcaption>network tab while navigating via anchor tag</figcaption></figure><h4><strong>3. Code splitting:</strong></h4><ul><li>Next.Js does this by default, it bundles the js files at page level.</li><li>Also bundles the common modules separately, so that it doesn’t need to refetch them for each page.</li></ul><p>To see this in action, lets build our app using:</p><pre>npm run build</pre><p>During this build, Next.Js has generated some static html files for our pages (first and signin) along with there js and css files in<em> /.next</em> folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*i_ovk_ZdPmXe0qFuHZlo-A.png" /><figcaption>Code splitting: build files generated at page level (highlighted in yellow)</figcaption></figure><p>We can see all the 3 pages - <em>index</em>, <em>first</em> and <em>signin</em> html files generated along with there js files individually.<br>so, code splitting done without any hustle with Next.js inbuilt feature.</p><h4>4. Prefetching</h4><ul><li>Next.Js can prefetch the next possible pages and enhance the rendering and performance of our app.</li></ul><p>To test this lets add a <em>Link</em> component in index page, this will route the user to signIn page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*Ewb6F57505TaRwsOnETK4w.png" /><figcaption>Added Link component in home page routing to signin page</figcaption></figure><ul><li>Now lets load the app in production mode, by running</li></ul><pre>npm run build<br><br>npm start</pre><p>Now on loading the app <em>index</em> page and inspecting the network tab, we can see the sigin in page js also loaded</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ep8jrJV08cCz0IDXh9spw.png" /><figcaption>Index page loaded along with sigin in bundle (prefetched)</figcaption></figure><p>whenever a <em>Link</em> components appear in the browser’s viewport, Next.js automatically <strong>prefetches</strong> the code for the linked page in the background.</p><h3>Conclusion:</h3><p>In this quick story we came to know how to get started with Next.js and explored below concepts:</p><ul><li>Create routes as files under “pages” folder</li><li>Use the built-in <em>Link</em> component for client side navigation</li><li>Automatic does code splitting and only loads what’s necessary for that page</li><li>Prefetches code/js in background for related page automatically</li></ul><p>Doing all of this in a react app from scratch will take a lot of boiler plate coding and time consuming but Next.js makes these happen by default.</p><p>To know more on Next.js in built features, checkout below story:</p><p><a href="https://medium.com/@muthukumarana/next-js-assets-metadata-scripts-styles-8621fc15d2bf">Next.Js - Assets, Metadata, Scripts, Styles</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7922b7f27bc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graphql - Operations (Query, Mutation, Subscription)]]></title>
            <link>https://medium.com/@muthukumarana/graphql-operations-query-mutation-subscription-951b948d78f?source=rss-8becd093b18------2</link>
            <guid isPermaLink="false">https://medium.com/p/951b948d78f</guid>
            <category><![CDATA[graphql-mu]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphiql]]></category>
            <category><![CDATA[express-graphql]]></category>
            <category><![CDATA[graphql-queries]]></category>
            <dc:creator><![CDATA[Muthu Kumaran]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 09:30:44 GMT</pubDate>
            <atom:updated>2023-04-24T10:03:28.712Z</atom:updated>
            <content:encoded><![CDATA[<p>What are queries and mutation in Graphql and how to do them ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*QObMF1gUxTb4qCI4zO6yQQ.png" /></figure><p>If you already know what Graphql is then continue here, if not then I suggest you take a quick reads on this</p><ul><li><a href="https://medium.com/@muthukumarana/graphql-ddc022349342">GraphQL</a></li><li><a href="https://medium.com/@muthukumarana/graphql-as-a-service-with-express-js-d784f3e1fb5f">GraphQL as a service with Express Js</a></li></ul><h3><strong>Graphql operations:</strong></h3><p>Graphql requests basically contains a string that holds the data and parameters to a graphql service. These queries will have a operation name and type.</p><ul><li>Operation name: Its something that we provide, which is unique and relevant to the operation that we perform</li><li>Operation type: Its either <em>query</em>, <em>mutation</em>, or <em>subscription</em>, by default if we don’t mention any type, it will be considered as Query</li><li>It is a convention to do all write operations using type <em>mutation</em></li><li>It uses <em>subscription </em>for all event driven or server sent event operations</li><li>Rest all fetch operation can use <em>Query</em> type</li></ul><p>To understand more of this and see how the are done, lets see them with an example one by one</p><h3><strong>Operation</strong> <strong>Query</strong></h3><p>Create a graphql service using “graphql”, “express”, and “express-graphql” modules, as shown below:</p><pre>const { buildSchema } = require(&#39;graphql&#39;);<br>const express = require(&#39;express&#39;);<br>const { graphqlHTTP } = require(&#39;express-graphql&#39;);<br><br>const schema = buildSchema(`<br>    type Person {<br>        id: Int<br>        name: String<br>        age: Int,<br>        gender: String<br>    }<br>    type Query {<br>        getPerson: [Person]<br>    }<br>`);<br><br>const data = [<br>    { id: 1, name: &quot;tom&quot;, age: 10, gender: &quot;M&quot; },<br>    { id: 2, name: &quot;jerry&quot;, age: 20, gender: &quot;M&quot; },<br>    { id: 3, name: &quot;micky&quot;, age: 30, gender: &quot;M&quot; },<br>    { id: 4, name: &quot;mini&quot;, age: 40, gender: &quot;F&quot; },<br>]<br>const rootValue = {<br>    getPerson: () =&gt; {<br>        return data<br>    }<br>};<br>const app = express();<br>app.use(&#39;/graphql&#39;, graphqlHTTP({ schema, rootValue, graphiql: true }));<br>app.listen(4000);<br>console.log(&#39;Running a GraphQL API server at http://localhost:4000/graphql&#39;);</pre><p>In above code, we have declared a schema with type “Person” and a query “getPerson”. Our query “getPerson” has its corresponding function in the “rootValue”, which returns an array of “Person” type objects.</p><p>On running the above code and by hitting <em>“</em><a href="http://localhost:4000/graphql"><em>http://localhost:4000/graphql</em></a><em>”, </em>we’ll get the GraphiQL ui. <br>For starters lets get “name” and “age” of all person using the “getPerson” query</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVCyHTuHzK1yxgu9cuN8HQ.png" /><figcaption>Get only the name and age of all persons</figcaption></figure><h4><strong>Graphql </strong>Arguments</h4><p>Above query worked great. But if we want the details of only one particular person say “tom”, then we have to pass a parameter and handle the same. Lets see how to do that.</p><p>1. Update the “getPerson” query in schema to take a parameter “name” of type String</p><pre> type Query {<br>    getPerson(name: String): [Person]<br>  }</pre><p>2. Update the corresponding method, that takes a argument as input, let deconstruct it and get “name” out of it. And return the filtered array based on the name.</p><pre>getPerson: ({ name }) =&gt; {<br>      let persons = data;<br>      if (name) persons = persons.filter((d) =&gt; d.name === name)<br>      return persons;<br>  }</pre><p>3. Now all that we have to do is, pass the “name” in query string with the value “tom” as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOJJwuZPkOm9Fw069n1_QA.png" /><figcaption>Passing a property “name” with value “tom”</figcaption></figure><p>For above request the payload will be like</p><pre>{<br>  &quot;query&quot;:&quot;{\n  getPerson(name: \&quot;tom\&quot;) {\n    id\n    name\n    age\n  }\n}&quot;,<br>  &quot;variables&quot;:null<br>}</pre><h4><strong>Graphql Variables</strong></h4><p>But hardcoding the value “tom” in the query string wont make it dynamic, and its hard to manipulate the string. So the better way is to pass the parameter in the variable property and have a placeholder in query string.</p><p>For this we have to update our query string as shown below, where we wrap the existing query string with a operation name “GetPerson” that takes a string parameter “$name”. And add a property “name” to variable with value “tom”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDBZmAsbjWoOhze1hmZ5Rg.png" /></figure><p>And the payload will looks like this:</p><pre>{<br>  &quot;query&quot;:&quot;query GetPerson($name: String) {\n  getPerson(name: $name) {\n    id\n    name\n    age\n  }\n}\n&quot;,<br>  &quot;variables&quot;:{&quot;name&quot;:&quot;tom&quot;},<br>  &quot;operationName&quot;:&quot;GetPerson&quot;<br>}</pre><p>Thus the query string remains same, and we use the variables to pass our parameters.</p><h3>Graphql Mutation</h3><p>Mutation are same as query except few changes in code to make it different from operation query type.</p><p>Lets create a mutation “createPerson” in our schema</p><pre>type Mutation {<br>  createPerson(name: String, age: Int, gender: String): Person<br>}</pre><p>And add below corresponding method to it in our rootValue</p><pre> createPerson: ({ name, age, gender }) =&gt; {<br>    const person = {<br>        id: data[data.length - 1].id + 1,<br>        name,<br>        age,<br>        gender<br>    }<br>    data.push(person);<br>    return person;<br>},</pre><p>Above method add a new person to the array that we have and returns the new person with a Id.</p><p>Now lets test this in GraphiQL,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5CvZYnkoQuqywxNAZ74HA.png" /></figure><p>So from above example its very clear that, query and mutation operates the same way, its just that syntax differ and its good to follow the convention (strictly use mutation for write operations)</p><h3>Graphql subscriptions</h3><p>This is the operation in which, the client subscribes to a server event and gets intimated by the server on that event trigger, with some data (a basc pub-sub model).</p><p>Will cover the subscription demo in the upcoming “apollographql” topics. Apollo is a great library to create your Graphql server and client.</p><p><strong>Conclusion:</strong></p><ul><li>We saw how to pass variables / parameters in queries, And found <em>mutation</em> is same as <em>query</em>.</li><li>Operation names or query names should be explicit and unique. so that its easy to identify it in code base, while debugging, logging etc.</li><li>Similarly using types will help in differentiate them (fetch or write operation), can be also useful on the server side to identify different GraphQL requests.</li></ul><p>Code: <a href="https://github.com/muthu1988/graphql/blob/main/graphql-server/graphql-query-mutation.js">https://github.com/muthu1988/graphql/blob/main/graphql-server/graphql-query-mutation.js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=951b948d78f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL as a service with Express Js]]></title>
            <link>https://medium.com/@muthukumarana/graphql-as-a-service-with-express-js-d784f3e1fb5f?source=rss-8becd093b18------2</link>
            <guid isPermaLink="false">https://medium.com/p/d784f3e1fb5f</guid>
            <category><![CDATA[express-graphql]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphiql]]></category>
            <dc:creator><![CDATA[Muthu Kumaran]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 03:25:33 GMT</pubDate>
            <atom:updated>2023-04-24T09:33:12.481Z</atom:updated>
            <content:encoded><![CDATA[<p>GraphQL as a service and how to consume</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*gpOJqhTeVpKUfLAg25rV5A.png" /></figure><p>If you know what is GraphQL and just want to see how it works with express, then please continue. If not please take a quick read on this story.</p><p><a href="https://medium.com/@muthukumarana/graphql-ddc022349342">GraphQL</a></p><blockquote>GraphQL need to be exposed as restful web service so that it can be consumed as an API from some frontend or other backend stacks over HTTP protocol</blockquote><p>One of the easiest way is to use <strong><em>express</em></strong> and <strong><em>express-graphql</em></strong> node modules. Lets see how that works,</p><ol><li>First we’ll install all required libraries:</li></ol><pre>npm i graphql express express-graphql</pre><p>2. Define a schema with type “Person” along with a query “person”</p><pre>const { buildSchema } = require(&#39;graphql&#39;);<br><br>const schema = buildSchema(`<br>    type Person {<br>        id: Int<br>        name: String<br>        age: Int,<br>        gender: String<br>    },<br>    type Query {<br>        person: Person<br>    }<br>`);</pre><p>3. Create rootValue, this will hold the function for our “person” query, along with that we’ll create a data on which the query is to be executed</p><pre>const data = { id: 1, name: &quot;tom&quot;, age: 10, gender: &quot;M&quot; };<br><br>const rootValue = {<br>    person: () =&gt; {<br>        return data<br>    }<br>};</pre><p>4. And the final step, we’ll use graphqlHTTP method of “express-graphql” to create a route in express server</p><pre>const app = express();<br>app.use(&#39;/graphql&#39;, graphqlHTTP({ schema, rootValue, graphiql: true }));<br>app.listen(4000);<br>console.log(&#39;Running a GraphQL API server at http://localhost:4000/graphql&#39;);</pre><p>In the above code, you can see a route ‘<em>/graphql’</em> created with “<em>graphqlHTTP</em>” method as a handler.</p><p><strong><em>graphqlHTTP</em></strong> - takes schema, rootValue (just like graphql node module), but it takes one more property “graphiql” with value “true”. <strong>GraphiQL</strong> is an in-browser tool for writing, validating, and testing GraphQL queries.</p><p>Putting all together it will look like this:</p><pre>const { buildSchema } = require(&#39;graphql&#39;);<br>const express = require(&#39;express&#39;);<br>const { graphqlHTTP } = require(&#39;express-graphql&#39;);<br><br>const schema = buildSchema(`<br>    type Person {<br>        id: Int<br>        name: String<br>        age: Int,<br>        gender: String<br>    }<br>    type Query {<br>        person: Person<br>    }<br>`);<br><br>const data = { id: 1, name: &quot;tom&quot;, age: 10, gender: &quot;M&quot; };<br><br>const rootValue = {<br>    person: () =&gt; {<br>        return data<br>    }<br>};<br>const app = express();<br>app.use(&#39;/graphql&#39;, graphqlHTTP({ schema, rootValue, graphiql: true }));<br>app.listen(4000);<br>console.log(&#39;Running a GraphQL API server at http://localhost:4000/graphql&#39;);</pre><p>5. On running this code, we can see the express server up and running on port 4000. On hitting “http://localhost:4000/graphql” in browser will render the GraphiQL ui</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVkcPAjLgU6puL7ZoY3trw.png" /></figure><p>Lets try a simple query, to get the name and age from the “person” query</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VW9SRKT9Lxdr425scLTD6Q.png" /></figure><p>To do the same without GraphiQL we can call the service just like a restful api using below curl</p><p><em>curl — location — request POST ‘localhost:4000/graphql’ — header ‘Content-Type: application/json’ — data-raw ‘{“query”: “{person{name age}}”, “variables”: null}’</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPs5_hRK7x2RV9NJ8jIGmw.png" /></figure><p>Also, POSTMAN too provides an option to make GraphQL calls, just like GraphiQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Nxmw2FEocUK8OzLjGmf1g.png" /></figure><p>Conclusion:</p><p>Yes, Graphql operates just like a restful service with its own cool feature.</p><p>Code is in below repo, feel free to clone and play around. Happy learning..<br><a href="https://github.com/muthu1988/graphql/blob/main/graphql-server/withexpress.js">https://github.com/muthu1988/graphql/blob/main/graphql-server/withexpress.js</a></p><p>Further reads:</p><p><a href="https://medium.com/@muthukumarana/graphql-operations-query-mutation-subscription-951b948d78f">Graphql - Operations (Query, Mutation, Subscription)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d784f3e1fb5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL]]></title>
            <link>https://medium.com/@muthukumarana/graphql-ddc022349342?source=rss-8becd093b18------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddc022349342</guid>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Muthu Kumaran]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 03:24:01 GMT</pubDate>
            <atom:updated>2023-04-13T03:50:44.454Z</atom:updated>
            <content:encoded><![CDATA[<p><em>ABC of Graphql, with a quick demo</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFMipglrmo3RbG53RVnbGg.png" /></figure><p><strong>What is Graphql:</strong></p><ul><li>A query language for our API</li><li>Provides complete description of the data in our API</li><li>Empowers consumer to request for exactly what they want</li><li>Can access not just the properties of one resource but also smoothly follow references between them</li></ul><p><strong>How it works:</strong></p><ul><li>Types &amp; Fields: GraphQL service is created by defining types and fields on those types</li><li>Functions: Then it provides functions for each field on each type</li><li>Service: Typically it will be a web service with a URL, that receives queries to validate and execute.</li><li>Produce Results: First it ensures the query matches the defined types and then executes the corresponding function to get results.</li></ul><p>Lets see how GraphQL does all of these.</p><p><strong>Basic setup:</strong></p><ol><li>Create a node project: <em>npm init</em></li><li>Install graphql node module: <em>npm install graphql</em></li><li>Create a schema, to define the structure of data:</li></ol><pre>    type Person {<br>        id: Int<br>        name: String<br>        age: Int,<br>        gender: String,<br>        address: Address<br>    }<br>    type Address {<br>        city: String,<br>        state: String,<br>        country: String<br>    }<br>    type Query {<br>        person: Person<br>    }</pre><p>Schema — has types <strong>Person</strong> &amp; <strong>Address</strong>, one query <strong>person</strong> to return<strong> Person </strong>data</p><p>4. Create a function for the query (person)in the schema</p><pre> person: () =&gt; {<br>        return { <br>          name: &quot;muthu&quot;, age: 30, gender: &quot;M&quot;, <br>          address: { city: &#39;CH&#39;, state: &#39;TN&#39;, country: &#39;IN&#39; } <br>        }<br>    }</pre><p>person function — that gets mapped to the Query ‘<strong>person’</strong> in the schema. It returns a hardcoded person object (ideally will get data from our data source)</p><p>5. Lets create that actual query that gets passed to the graphql, say for example if I want only the name and age. Then the query will look like this.</p><pre>{ <br>    person { <br>        name,<br>        age<br>    }<br>}</pre><p>we are querying graphql only for the name and age as of now.</p><p>6. Now to connect all of this, we’ll use the <em>graphql </em>and <em>buildSchema</em> apis of <strong>graphql</strong> library</p><pre>const { graphql, buildSchema } = require(&#39;graphql&#39;);<br>const schema = buildSchema(``);<br>const rootValue = {};<br>const source = ``;<br>graphql({ schema, source, root }).then((response) =&gt; {<br>    console.log(JSON.stringify(response));<br>});</pre><p><strong><em>buildSchema</em></strong><em> </em>method will take a schema defined.<br><strong><em>rootValue</em></strong> will have the function (person function) for the defined query in schema<br><strong><em>source</em></strong><em> </em>will be the query string for the data to be fetched<br><strong><em>graphql</em></strong> method takes all of these as input and generates the result.</p><p>7. After placing the schema, function and query string in the right place, it will look like this:</p><pre>const { graphql, buildSchema } = require(&#39;graphql&#39;);<br><br>const schema = buildSchema(`<br>    type Person {<br>        id: Int<br>        name: String<br>        age: Int,<br>        gender: String,<br>        address: Address<br>    }<br>    type Address {<br>        city: String,<br>        state: String,<br>        country: String<br>    }<br>    type Query {<br>        person: Person<br>    }<br>`);<br><br>const rootValue = {<br>    person: () =&gt; {<br>        return {<br>            name: &quot;muthu&quot;, age: 30, gender: &quot;M&quot;,<br>            address: { city: &#39;CH&#39;, state: &#39;TN&#39;, country: &#39;IN&#39; }<br>        }<br>    }<br>};<br><br>const source = `{ <br>    person { <br>        name,<br>        age<br>    }<br>}`;<br><br>graphql({ schema, source, rootValue }).then((response) =&gt; {<br>    console.log()<br>    console.log(JSON.stringify(response));<br>    console.log()<br>});</pre><p>On execution, we’ll got only the name and age as expected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*15SAZI_AJisqtb8Z9ZwdPA.png" /><figcaption>graphql promise resolved with above object</figcaption></figure><p>As requested in the query string (source in code), we got only the name and age.</p><h4><strong>Lets modify the query string and play around:</strong></h4><pre>// Request only the name<br>const source = `{ <br>    person { <br>        name<br>    }<br>}`;<br><br>// Generated result<br>{&quot;data&quot;:{&quot;person&quot;:{&quot;name&quot;:&quot;muthu&quot;}}}</pre><pre>// Request only the city (nested objects parameter)<br>const source = `{ <br>    person {<br>        address {<br>            city<br>        }<br>    }<br>}`;<br><br>// Generated result<br>{&quot;data&quot;:{&quot;person&quot;:{&quot;address&quot;:{&quot;city&quot;:&quot;CH&quot;}}}}</pre><pre>// Request for property thats not in schema (region property no defined)<br>const source = `{ <br>    person {<br>        address {<br>            city,<br>            region<br>        }<br>    }<br>}`;<br><br>// Generated result<br>{&quot;errors&quot;:[{<br>  &quot;message&quot;:&quot;Cannot query field \&quot;region\&quot; on type \&quot;Address\&quot;.&quot;<br>}]}</pre><pre>// Request for subtype without any properties <br>// for address we didn&#39;t mention what we want<br>const source = `{ <br>    person {<br>        name<br>        address<br>    }<br>}`;<br><br>// Generated result<br>{&quot;errors&quot;:[{<br>  &quot;message&quot;:&quot;Field \&quot;address\&quot; of type \&quot;Address\&quot; must have a <br>   selection of subfields. Did you mean \&quot;address { ... }\&quot;?&quot;,<br>}]}</pre><h4><strong>Conclusion:</strong></h4><p>This clearly proves that Graphql is a query language with defined data, that validates the request and returns exactly what is requested.</p><p>Code is available in below repo, feel free to clone and play around:<br><a href="https://github.com/muthu1988/graphql/blob/main/graphql-server/basic.js">https://github.com/muthu1988/graphql/blob/main/graphql-server/basic.js</a></p><p>Explore more:</p><p><a href="https://medium.com/@muthukumarana/graphql-as-a-service-with-express-js-d784f3e1fb5f">GraphQL as a service with Express Js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddc022349342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux — As Is, with Saga or Thunk]]></title>
            <link>https://medium.com/@muthukumarana/redux-as-is-with-saga-or-thunk-1ad0913fee50?source=rss-8becd093b18------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ad0913fee50</guid>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <category><![CDATA[redux-middleware]]></category>
            <category><![CDATA[redux-saga]]></category>
            <dc:creator><![CDATA[Muthu Kumaran]]></dc:creator>
            <pubDate>Tue, 13 Dec 2022 07:05:59 GMT</pubDate>
            <atom:updated>2022-12-13T07:05:59.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>Redux — As Is, with Saga or Thunk</h3><p>Redux, what it does and what are redux-saga and redux-thunk</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*CcdVqwLhamJMl7Yf6ufHBw.png" /></figure><h4><strong>Redux</strong>:</h4><ul><li>Pattern and library for managing and updating application state, using events called “actions”.</li><li>A centralized store for state that needs to be used across your entire application.</li></ul><h4><strong>Basic terminologies:</strong></h4><ul><li><em>store: </em>tree object that stores the whole global state of the application</li><li><em>action: </em>an object that describes what happens to the state</li><li><em>dispatch: </em>update the store with action</li><li><em>reducer: </em>function that takes and creates a new state from old state and action</li></ul><h4><strong>Why middleware (thunk or saga):</strong></h4><ul><li>Lets say we want to fetch data from a API and persist it in our redux store.</li><li>Challenge here is, we have to dispatch an action only on completion of the API call (success / failure).</li><li>So we need some middleware which runs the asynchronous tasks and dispatch the required action.</li></ul><blockquote>This is where middleware like thunk and saga comes into picture.</blockquote><h4><strong>Redux As Is:</strong></h4><p>For this lets use “ Redux Toolkit”, a standard way to implement redux to our application with following steps:</p><ol><li>create a node project by running “npm init”</li><li>install redux tool kit “npm install @reduxjs/toolkit”</li><li>create actions and reducer using “createSlice” with:<br>- name: “bored”<br>- initial state: empty array of “activities”<br>- actions: “getActivities”, “resetActivities”</li></ol><p>4. export boredSlice ( for reducer) and its actions (“getActivities”, “resetActivities”)</p><pre>// src\slices\boredSlice.js<br><br>import { createSlice } from &#39;@reduxjs/toolkit&#39;;<br><br>// A function that return a radom activity from a static array of activities<br>const fetchActivity = () =&gt; {<br>    const activities = [&#39;Go to a local thrift shop&#39;, <br>        &#39;Go to a music festival with some friends&#39;, <br>        &#39;Bake pastries for you and your neighbor&#39;, <br>        &#39;Contribute code to an open-source software project&#39;, <br>        &#39;Organize your movie collection&#39;, <br>        &#39;Have a photo session with some friends&#39;, <br>        &#39;Do something nice for someone you care about&#39;, <br>        &#39;Shred old documents you don\&#39;t need anymore&#39;, <br>        &#39;Study a foreign language&#39;, <br>        &#39;Take a spontaneous road trip with some friends&#39;<br>    ];<br>    return activities[Math.floor(Math.random() * 10)];<br>}<br>/**<br> * Creates a reducer<br> * name: &quot;bored&quot;, inital state: &quot;activities: []&quot;, <br> * actions: &quot;getActivities, resetActivities&quot;<br> */<br>const boredSlice = createSlice({<br>    name: &#39;bored&#39;,<br>    initialState: {<br>        activities: []<br>    },<br>    reducers: {<br>        getActivities: state =&gt; {<br>            state.activities.push(fetchActivity())<br>        },<br>        resetActivities: state =&gt; {<br>            state.activities = [];<br>        },<br>    },<br>});<br><br>export const { getActivities, resetActivities } = boredSlice.actions;<br>export default boredSlice;</pre><p>5. Create store using “configureStore” and add the boredSlice reducer in index.js file</p><pre>// src\index.js<br>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br>import boredSlice, { getActivities } from &#39;./slices/boredSlice&#39;;<br><br>const store = configureStore({<br>    reducer: {<br>        bored: boredSlice.reducer<br>    }<br>});<br><br>// Subscribe to log store change<br>store.subscribe(() =&gt; {<br>    const state = store.getState();<br>    console.log(state)<br>});<br><br>// dispatch getActivities action<br>store.dispatch(getActivities());</pre><p>6. subscribe to store and dispatch “getActivities” action, while executing we will get bored store with activities array getting updated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*-zeQ8eRzEoFGd_PHc5SpnA.png" /></figure><p>So far its good, we don’t have any async operations involved. But say if we want to get the activity from an api rather than hard coded in “fetchActivity”. Then we can use “thunk” or “saga”, let see them one by one.</p><h3>Redux Thunk:</h3><p>For this lets use “createAsyncThunk” from “ Redux Toolkit”, with following steps:</p><ol><li>Use “createAsyncThunk” to make the “fetchActivity” as thunk method, which has a async api call to “https://www.boredapi.com/api/activity” with axios library (removing the hard coded activities that we had earlier)</li></ol><pre>// src\slices\boredSlice.js<br>import { createSlice, createAsyncThunk } from &#39;@reduxjs/toolkit&#39;;<br>import axios from &#39;axios&#39;;<br><br>// Redux thunk method for async operations<br>export const fetchActivity = createAsyncThunk(&#39;bored/activity&#39;, async () =&gt; {<br>    const response = await axios.get(&#39;https://www.boredapi.com/api/activity&#39;)<br>    return response.data.activity<br>})<br></pre><p>2. Inside createSlice use “extraReducers” callback to handle the thunk method actions, as shown below</p><pre>// src\slices\boredSlice.js<br>import { createSlice, createAsyncThunk } from &#39;@reduxjs/toolkit&#39;;<br>import axios from &#39;axios&#39;;<br><br>// Redux thunk method for async operations<br>export const fetchActivity = createAsyncThunk(&#39;bored/activity&#39;, async () =&gt; {<br>    const response = await axios.get(&#39;https://www.boredapi.com/api/activity&#39;)<br>    return response.data.activity<br>})<br><br>const boredSlice = createSlice({<br>    name: &#39;bored&#39;,<br>    initialState: {<br>        activities: [],<br>        status: &#39;idle&#39;<br>    },<br>    reducers: {<br>        resetActivities: state =&gt; {<br>            state.activities = [];<br>            state.status = &#39;idle&#39;;<br>        },<br>    },<br>    // callback that receives a builder object to define case reducers <br>    // for thunk status <br>    extraReducers(builder) {<br>        builder<br>            .addCase(fetchActivity.pending, (state, action) =&gt; {<br>                state.status = &#39;loading&#39;<br>            })<br>            .addCase(fetchActivity.fulfilled, (state, action) =&gt; {<br>                state.status = &#39;succeeded&#39;<br>                state.activities = state.activities.concat(action.payload)<br>            })<br>            .addCase(fetchActivity.rejected, (state, action) =&gt; {<br>                state.status = &#39;failed&#39;<br>                state.error = action.error.message<br>            })<br>    }<br>});<br><br>export const { resetActivities } = boredSlice.actions;<br>export default boredSlice;</pre><p>In above code there are 3 cases for handling the asyn thunk status</p><ul><li>pending: gets invoked when the thunk method is triggered (api call)</li><li>fulfilled: gets invoked when the api call is completed successfully</li><li>rejected: gets invoked when the api call fails</li></ul><p>In all 3 cases we update the state accordingly.</p><p>3. In index.js import “fetchActivity” async action thunk and dispatch the same as shown below:</p><pre>// src\index.js<br>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br>import boredSlice, { fetchActivity } from &#39;./slices/boredSlice&#39;;<br><br>const store = configureStore({<br>    reducer: {<br>        bored: boredSlice.reducer<br>    }<br>});<br><br>// Subscribe to log store change<br>store.subscribe(() =&gt; {<br>    const state = store.getState();<br>    console.log(state)<br>});<br><br>// dispatch fetchActivity action<br>store.dispatch(fetchActivity());</pre><p>4. Subscribe to store and dispatch “fetchActivity” action, while executing we will get bored store updated with data from API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*dS8vvawTVEDwZc1f_-CdgQ.png" /></figure><p>From above, we can see state change happening twice</p><ul><li>Once while invoking the thunk action, it update the state to ‘loading’</li><li>And on successful fetch, the “activities” array in state is updated with api response and the “status” changed to “succeeded”</li></ul><p>So simple as that, now we have handled async call with less code change thus enabling async operations.</p><h3>Redux Saga</h3><p>Lets see how the same can be done using saga, with following steps:</p><ol><li>To start, lets create a separate saga file as the existing slice can’t be used as is</li></ol><pre>// src\sagas\boredSaga.js<br>import { all, put, takeEvery } from &#39;redux-saga/effects&#39;<br>import axios from &#39;axios&#39;;<br><br>// Our worker Saga: will perform the async ajax call<br>export function* getActivity() {<br>    const response = yield axios.get(&#39;https://www.boredapi.com/api/activity&#39;)<br>    yield put({ type: &#39;GET_ACTIVITY&#39;, payload: response.data.activity })<br>}<br><br>// Our watcher Saga: spawn a new getActivity task on each GET_ACTIVITY<br>export function* watchGetActivity() {<br>    yield takeEvery(&#39;GET_ACTIVITY_ASYNC&#39;, getActivity)<br>}<br><br>export default function* rootSaga() {<br>    yield all([<br>        watchGetActivity()<br>    ])<br>}</pre><p>Sagas will require below generator functions (function with *), that yields objects which are kind of instructions to middleware</p><ul><li>worker saga: “getActivity” function that makes that actual API call</li><li>watcher saga: “watchGetActivity” which triggers the worker saga for every dispatch</li><li>root saga: “rootSaga”, used to starts all the sagas in the file (in our case its just one)</li></ul><p>2. Now we need a reducer for our saga, to handle all its actions and update state</p><pre>// src\sagas\reducers.js<br>export default function counter(state = { activities: [] }, action) {<br>    switch (action.type) {<br>        case &#39;GET_ACTIVITY&#39;:<br>            return { ...state, activities: [...state.activities, action.payload] }<br>        default:<br>            return state<br>    }<br>}</pre><p>this reducer with type “GET_ACTIVITY” will be used by our worker saga on api success to update the store state.</p><p>3. Finally we need to configure the saga middleware in our redux state using “createSagaMiddleware” from “redux-saga” as shown below. For this we have created a new index file names “sagaIndex.js”</p><pre>// src\sagaIndex.js<br>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br>import createSagaMiddleware from &#39;redux-saga&#39;;<br>import reducer from &#39;./sagas/reducers&#39;;<br>import rootSaga from &#39;./sagas/boredSaga&#39;;<br><br>// saga specific code<br>const sagaMiddleware = createSagaMiddleware()<br>sagaMiddleware.run(rootSaga);<br><br>export const store = configureStore({<br>    reducer,<br>    middleware: (getDefaultMiddleware) =&gt;<br>        getDefaultMiddleware().concat([sagaMiddleware]), // saga as middleware<br>})<br><br>store.subscribe(() =&gt; {<br>    const state = store.getState();<br>    console.log(state)<br>});<br><br>// dispatch get activity saga action<br>store.dispatch({ type: &#39;GET_ACTIVITY_ASYNC&#39; });</pre><p>4. Subscribe to store and dispatch “GET_ACTIVITY_ASYNC” action, while executing sagaIndex.js, we will get bored store updated with data from API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*gSmk9gIHhSOraBIpzklp7w.png" /></figure><p>From above, we can see state change happening twice</p><ul><li>While invoking the saga action, it update the state with empty activities</li><li>On successful fetch the “activities” array in state is updated with api response</li></ul><p>Thus we have handled async API calls in saga way, can’t say its as simple as thunk.</p><p><strong>Conclusion:</strong></p><ol><li>Either <em>thunk</em> or <em>saga</em>, both solved the async problem successfully.</li><li>Lines of code: <br> <em>Thunk</em>: 1 slice file with one thunk function, and a call back function to watch and update state based on asyn operation status<br><em>Saga</em>: 1 saga file with 2 generator functions (worker and listener) and 1 reducer</li><li>Complexity<br><em>Thunk</em>: No action type required with RTK in place, and thunk async functions returns a function that can be dispatched with payload.<br><em>Saga</em>: Requires an action type, need generator functions, and saga apis methods, also need to maintain action types to dispatch a action.</li><li>Learning curve &amp; Coding:<br><em>Thunk</em>: small learning curve, implementation is very straight forward.<br><em>Saga</em>: Needs some learning to be done, as knowledge on generator functions, saga apis is a must. And amount of code and readability is high compared to thunk.</li></ol><p><strong>Bonus: <br></strong>If you like to play around with the code, feel free to clone this git repo:<br><a href="https://github.com/muthu1988/redux-thunk-and-saga">https://github.com/muthu1988/redux-thunk-and-saga</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ad0913fee50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Lazy: Why ? What ? How ?]]></title>
            <link>https://medium.com/@muthukumarana/react-lazy-why-what-how-e620c7456cc8?source=rss-8becd093b18------2</link>
            <guid isPermaLink="false">https://medium.com/p/e620c7456cc8</guid>
            <category><![CDATA[react-lazy]]></category>
            <category><![CDATA[react-advanced-patterns]]></category>
            <category><![CDATA[code-splitting]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[react-core-concept]]></category>
            <dc:creator><![CDATA[Muthu Kumaran]]></dc:creator>
            <pubDate>Sun, 21 Aug 2022 14:00:15 GMT</pubDate>
            <atom:updated>2022-08-22T03:05:55.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Lazy: Why ? What ? How ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*J1WAmOJjxUULGtrBfaeEuw.png" /></figure><p>Before jumping into React lazy, there are few thing we need to understand:</p><ol><li><strong>Bundling</strong>:<br>All our react code gets bundled into one single file, and gets loaded in the browser/client to render the dom.</li><li><strong>Largest Contentful pain (LCP)</strong>greater that 1.2 Sec: <br>This is one of the performance issue that you might encounter in your react applications when our bundle size is bigger. It makes the main content of our page to load slower.</li><li><strong>Code splitting</strong>:<br>Technique that helps us “lazy load” the code/javascript that is required for the current page or view, thus reducing the LCP and enhancing performance.</li></ol><blockquote>So in short, to improve performance we need to reduce the bundle size by code splitting and lazy load the javascript on demand.</blockquote><h4>Why ?</h4><p>To do code splitting we can use something called “dynamic imports”, <br>import(&quot;./stringUtils&quot;).then(stringUtils =&gt; {<br> console.log(stringUtils.toUpperCase(&quot;This is Dynamic Imports&quot;));<br>});<em><br></em>In Create React App, this syntax will automatically starts code-splitting your app. And for webpack it requires some additional configuration.</p><blockquote>So in React, to render a component using dynamic import we need React.lazy</blockquote><h4><strong>What ?</strong></h4><p>React.lazy is a function that takes an anonymous function as an input which in turn returns a dynamic import of the component (to be loaded lazily).<br>const LazyComponent = React.lazy(() =&gt; import(&#39;./LazyComponent&#39;));</p><p>This lazy component should be rendered inside react “Suspense” component which lets us to provide a fallback component until the Lazy component is loaded<br>import React, { Suspense } from &#39;react&#39;;</p><blockquote>Enough of theory, let see get our hands dirty</blockquote><h4>How ?</h4><p>To start, lets create a new react app using CreateReactApp and add 2 components:</p><ol><li>Parent component: Will be child in App Component and renders “Lazy component” after 5 seconds (line 9 to 11, Parent.js)</li><li>Lazy component: child component of “Parent component”, that lazy loads (line 16, Parent.js)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9lNp0mP8_SFvRv38ZVcGA.png" /><figcaption>Parent &amp; Lazy component</figcaption></figure><p>While rendering in browser, we can see a single bundle generated and loads at the start of the application. <br>“I am a lazy component” gets rendered after 5 seconds, but the javascript for it is rendered initially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x_ERSBJRmZCbYHJRhkPfAg.png" /><figcaption>App loaded with single bundle.js</figcaption></figure><p>Lets implement React.lazy and see how code splitting happens, through following steps:<br>1. Dynamic import: Replace import LazyComponent from ‘./Lazy’; with <br>const LazyComponent = React.lazy(() =&gt; import(‘./Lazy’)); in Parent.js (line 3, Parent.js)<br>2. Import “Suspense” component and wrap the Lazy component with it (line 1, 17 to 19 in Parent.js)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*ZICuPjvRY4Rr_60TfWQ0rw.png" /><figcaption>Parent.js with Lazy loaded child component</figcaption></figure><p>Now lets reload the application in client,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rx2kS4pkUPwwLxQkrNBiQA.png" /><figcaption>Lazy bundle loading after 5 seconds</figcaption></figure><p>Now we can see the bundle.js file that loads as usual. And we can see an another file “src_Lazy_js.chunk.js” loaded after 5 seconds.</p><p>Suspense component will help us to load a fallback component, while the lazy chunk file is loading.</p><blockquote>Thus lazily loading the JS for our component.</blockquote><p><strong>Summary:</strong></p><ol><li>We started with need for code splitting and lazy loading to enhance performance</li><li>Dynamic imports with React.lazy and load JS lazily.</li></ol><p><strong>Note</strong>: In this example it wont make much difference with respect to size and time for initial bundle, but incase of large application that has many modules and 3rd party libraries, it will make a huge difference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e620c7456cc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React memo Vs useMemo Vs useCallback -React functional Components]]></title>
            <link>https://medium.com/@muthukumarana/react-memo-vs-usememo-vs-usecallback-react-functional-components-e3bc01680778?source=rss-8becd093b18------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3bc01680778</guid>
            <category><![CDATA[usememo]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[react-memo]]></category>
            <category><![CDATA[functional-component]]></category>
            <dc:creator><![CDATA[Muthu Kumaran]]></dc:creator>
            <pubDate>Wed, 23 Feb 2022 09:13:56 GMT</pubDate>
            <atom:updated>2022-02-23T09:13:56.170Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a confusion between these three react API’s, and sometimes even used alternatively for one another by developers. Though the names and functionalities are quite similar, they are meant for solving different problem statements. So lets demystify them one by one.</p><h3><strong>React.memo :</strong></h3><ol><li>Is a Higher Order Component (HOC).</li><li>If your component rerenders the same way for the same given props, then “memo” prevents a rerender.</li></ol><p>Lets see this with an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jr5hNDQE_-dDF7JQ2jcmUw.png" /><figcaption>without “memo”</figcaption></figure><p>In above code, There are 3 components:</p><ol><li>App: parent component, with 2 input fields, these fields will update state value “a” and “b” using the useState hook.</li><li>ComponentA: child component of “App” that takes only one prop “a”</li><li>ComponentB: child component of “App” that takes only one prop “b”</li></ol><p>When “App” component renders for the first time, Both child components will get rendered as expected.</p><p>when we change the values in text field “a”, both “ComponentA” and “ComponentB” will get rerendered. But <strong>“ComponentB” doesn’t need to rerender for props “a” </strong>change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3FPpoxNBJpVd5wPrQXxn7Q.png" /></figure><p>Let bring “React.memo” into the action. As its a HOC, we can just wrap our componentB using the “memo” function and return a memoized function as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpDdZ_Gba_HqUxRTBXsuMQ.png" /></figure><p>Now when we change the value of “a” via the input field, we can see “ComponentB” not being rerendered (“Comonent B rendered” console log didn’t show up in logs, where as ComponentA was rerenderd multiple times)</p><p>Lets check what “useMemo” is up to and how it differed from “memo”</p><h3><strong>useMemo:</strong></h3><ol><li>Returns a <a href="https://en.wikipedia.org/wiki/Memoization">memoized</a> value.</li><li>Will only recompute the memoized value when one of its dependencies change on every rerender</li></ol><p>Lets see this with an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMyB9rIcd6_V-4Q7Rocr0Q.png" /><figcaption>complex computation without “useMemo”</figcaption></figure><p>In above code, There are 2 components and a function:</p><ol><li>App: parent component, with 2 input fields, these fields will update state value “a” and “b” using the useState hook.</li><li>ComponentA: child component of “App” that takes two props “a” and “b”</li><li>complexComputation: function that take in prop value “a” and returns a computized value on every rerender.</li></ol><p>ComponentA will rerender when we change the values in text field “a” or “b”. But our <strong>complexComputation</strong> function should<strong> recompute only on change of prop “a”</strong>.</p><p>Let bring “useMemo” into the action. Pass complexComputation function along with prop “a” in dependency array, to get a memoized value as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02Ib43W4ihUlo8l4BQCJgg.png" /><figcaption>getting memoized value using “useMemo”</figcaption></figure><p>Now when we change the value of prop “a”, the complexComputation function gets executed. But for the change of prop “b”, it didn’t recompute, thus successfully skipped a recomputation (“complex computation” log in console didn’t show up for prop “b” change).</p><p>Last stop, its time for useCallback.</p><h3>useCallback:</h3><ol><li>Returns a <a href="https://en.wikipedia.org/wiki/Memoization">memoized</a> version of a function.</li><li>memoized function will change only when any one of its dependencies change</li></ol><p>Lets check that with an example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFPSHUJTs_9Bw7j0I1BDhA.png" /><figcaption>memoized function using “useCallback” function</figcaption></figure><p>In above code, There are 2 components and a function:</p><ol><li>App: parent component, with 2 input fields, these fields will update state value “a” and “b” using the useState hook.</li><li>ComponentA: child component of “App” that takes two props “a” and “b”</li><li>methodToMemoize: function that take in prop value “b” and returns a json with values of prop “a” and prop “b”.</li><li>memoizedFunction: function created from “methodToMemoize” using “useCallback”</li></ol><p>This memoized function will not have a new value for prop “a” until prop “b” gets updated, since only prop “b” is in the dependency array.</p><p>So now we have a version of function with original object references of prop “a”, which is empty at initial render and prop “b” is still not updated as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*9ctvOcZ50qUVRFTpPIPUEQ.png" /><figcaption>value “a” remains empty as the memoized function is not updated (i.e props “b” not updated)</figcaption></figure><p>Lets update the value of prop “b”, now we can see the value of prop “a” getting changed, i.e we got a new version of function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*by_3VdKr2a08MkVPtTyiDw.png" /></figure><p>Note: This functionality is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders</p><h3>Conclusion:</h3><p>As we saw all these 3 APIs provide solution for different problem statement, so in a nut shell:</p><p><strong>memo</strong>: avoids component rerendering by checking the props</p><p><strong>useMemo</strong>: creates a memoized value to avoid expensive re-computations on components rerender</p><p><strong>useCallback</strong>: creates a memoized callback functions that gets passed to child to avoid rerender</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3bc01680778" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>