<?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 Aarthini on Medium]]></title>
        <description><![CDATA[Stories by Aarthini on Medium]]></description>
        <link>https://medium.com/@aarthinim?source=rss-756946511e09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Xhuhc_je7-fSVN9R</url>
            <title>Stories by Aarthini on Medium</title>
            <link>https://medium.com/@aarthinim?source=rss-756946511e09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:04:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aarthinim/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[Enhancing Web Accessibility: A Pathway to Inclusive Digital Experiences]]></title>
            <link>https://aarthinim.medium.com/enhancing-web-accessibility-a-pathway-to-inclusive-digital-experiences-b35d86720a52?source=rss-756946511e09------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35d86720a52</guid>
            <category><![CDATA[web-accessibility]]></category>
            <dc:creator><![CDATA[Aarthini]]></dc:creator>
            <pubDate>Wed, 31 May 2023 17:37:27 GMT</pubDate>
            <atom:updated>2023-06-01T08:34:21.800Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>In today’s digital age, the internet has become an integral part of our lives. From online shopping to accessing educational resources and connecting with others, the web offers countless opportunities. However, not everyone can fully participate in this digital realm. Many individuals with disabilities face significant barriers when navigating websites, hindering their ability to access information, engage with online services, and enjoy a seamless browsing experience. This is where web accessibility comes into play.</p><figure><img alt="Web Accessibility" src="https://cdn-images-1.medium.com/max/600/1*4SZT5B70euZQRdmfapAFVg.png" /><figcaption>Web Accessibility</figcaption></figure><h3>What is Web Accessibility?</h3><p>Web accessibility refers to the inclusive design and development of websites, applications, and digital content that can be accessed and used by individuals with disabilities. It aims to eliminate barriers and provide equal access to information and services for everyone, regardless of their abilities. By implementing web accessibility practices, we can create an inclusive online environment where individuals with disabilities can participate and contribute on an equal basis with others.</p><h3>Why is Web Accessibility Important?</h3><ol><li>Equal Access: Web accessibility ensures that individuals with disabilities have equal access to information, services, and opportunities online. It empowers them to be independent, make informed decisions, and engage fully in society.</li><li>Legal and Ethical Obligations: Many countries have implemented laws and regulations that require websites to be accessible. By complying with these standards, organizations can avoid legal issues and demonstrate their commitment to inclusivity and social responsibility.</li><li>Expanded Audience: By making your website accessible, you open up your content to a broader audience. This includes not only individuals with disabilities but also older adults, people with temporary impairments, and those using assistive technologies.</li><li>Improved User Experience: Web accessibility often goes hand in hand with good design practices. By optimizing your website for accessibility, you can enhance the user experience for all visitors, leading to increased engagement and customer satisfaction.</li></ol><h3>Key Principles of Web Accessibility:</h3><ol><li>Perceivable: Ensure that all users can perceive and understand the information presented on your website. This includes providing alternatives for non-text content (e.g., images), using clear and easy-to-read text, and making sure multimedia content is accessible.</li><li>Operable: Make your website easy to operate and navigate. This involves designing intuitive user interfaces, providing keyboard accessibility, and ensuring that users can navigate through the content in a logical and predictable manner.</li><li>Understandable: Ensure that your website is clear and easy to understand for all users. Use plain language, organize information in a coherent manner, and provide instructions and error messages that are easy to comprehend.</li><li>Robust: Build websites that are compatible with a wide range of devices, browsers, and assistive technologies. This ensures that users can access your content regardless of the technology they use.</li></ol><h3>Implementing Web Accessibility:</h3><ol><li>Use Semantic HTML: Utilize appropriate HTML elements to structure your content, making it more accessible to screen readers and other assistive technologies.</li><li>Provide Alternative Text: Add descriptive alt attributes to images, allowing users with visual impairments to understand their content.</li><li>Caption and Transcribe Multimedia: Include captions and transcripts for audio and video content, enabling individuals with hearing impairments to access the information.</li><li>Use ARIA Roles: Implement Accessible Rich Internet Applications (ARIA) roles to enhance the accessibility of dynamic content, such as menus, tooltips, and interactive elements.</li></ol><p>Here are some commonly used ARIA tags in web accessibility:</p><ul><li><strong>role : </strong>Specifies the role or type of an element. For example, <em>role=”button”</em> can be used to indicate that a <em>&lt;div&gt;</em> or <em>&lt;span&gt;</em> element functions as a button.</li><li><strong>aria-label </strong>: Provides a text alternative for an element when the visible label is not descriptive enough. It is used to convey the purpose or meaning of an element.</li><li><strong>aria-labelledby</strong> : References the ID of an element that serves as the label for the current element. It establishes a relationship between an element and its label.</li><li><strong>aria-describedby</strong> : References the ID of an element that provides additional descriptive information about the current element. It is used to associate additional information with an element, such as a tooltip or description.</li><li><strong>aria-hidden</strong> : Indicates that an element and its contents should be hidden from assistive technologies. It is useful for decorative elements or content that is not relevant to the accessibility experience.</li><li><strong>aria-diabled</strong> : Indicates that an interactive element is disabled and cannot be activated or selected. It informs assistive technologies that the element is not currently operable.</li><li><strong>aria-expanded</strong> : Indicates whether a collapsible element, such as an accordion or dropdown, is expanded or collapsed.</li><li><strong>aria-haspopup </strong>: Indicates that an element has a popup menu, dialog, or sub-level menu associated with it.</li><li><strong>aria-live </strong>: Specifies that an element should be announced by assistive technologies as soon as it changes. It is commonly used to provide live updates, such as in a chat application or a dynamically updating status.</li></ul><p>5. Conduct Accessibility Testing: Regularly test your website using automated tools, assistive technologies, and user feedback to identify and fix accessibility issues.</p><h3>Conclusion:</h3><p>Web accessibility is not just a legal requirement; it is a moral imperative. By prioritizing inclusive design and development practices, we can ensure that the digital landscape becomes a welcoming space for everyone. By implementing the key principles of web accessibility and embracing best practices, we can create a more inclusive internet that empowers individuals with disabilities and fosters equal opportunities for all. Let’s strive for a web that leaves no one behind and reflects the true diversity of our society</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35d86720a52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next-Gen Javascript]]></title>
            <link>https://aarthinim.medium.com/next-gen-javascript-327a0f10ba82?source=rss-756946511e09------2</link>
            <guid isPermaLink="false">https://medium.com/p/327a0f10ba82</guid>
            <category><![CDATA[es6-features]]></category>
            <category><![CDATA[spread-operator]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Aarthini]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 05:45:42 GMT</pubDate>
            <atom:updated>2023-11-08T09:05:24.596Z</atom:updated>
            <content:encoded><![CDATA[<h4>Features</h4><ul><li>let and const</li><li>Arrow functions</li><li>exports and imports</li><li>Classes</li><li>Spread and Rest parameters</li><li>Destructuring</li><li>Template Literals</li><li>Array functions</li><li>Async Code</li></ul><h4>let and const</h4><p><strong><em>let</em></strong></p><p>The <em>let</em> keyword is used to declare a block-scoped variable, which means that the variable is only accessible within the block in which it was declared. A block is defined by curly braces <em>{}</em></p><p><em>let </em>can be reassigned to other values, but they cannot be redeclared.</p><pre>if (true) { <br>   let x = 10;<br>   x=15; //reassigned<br>   console.log(x); // outputs 15 <br>} <br>console.log(x); // Uncaught ReferenceError: x is not defined<br>let y= 5;<br>let y= 10; // Error: Identifier &#39;x&#39; has already been declared<br></pre><p><strong><em>const</em></strong></p><p>The <em>const</em> keyword is used to declare a constant variable, which means that once a value is assigned to it, it cannot be reassigned. Like let, it is also block-scoped.</p><p><em>const </em>variables cannot be redeclared, and neither can they be reassigned to other values.</p><pre>const PI = 3.14;<br>PI = 3; // Uncaught TypeError: Assignment to constant variable.<br><br>if (true) {<br>  const x = 10;<br>  console.log(x); // outputs 10<br>}<br><br>console.log(x); // Uncaught ReferenceError: x is not defined</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*V4j5GZvzGE4S4T0FNgTZDA.png" /><figcaption>Difference between let, var, const</figcaption></figure><h4>Arrow Functions</h4><p>Arrow functions are a shorthand syntax for creating functions in JavaScript. It provide a more concise and expressive way to write function expressions.</p><pre><strong><em>Syntax</em></strong><br>(parameters) =&gt; { statements }</pre><ul><li>Parameters: A list of input parameters for the function, enclosed in parentheses. If the function takes no parameters, you can omit the parentheses or use an empty pair of parentheses<em> </em><strong><em>()</em></strong>.</li><li>Arrow: A fat arrow <strong>=&gt;</strong> that separates the parameters from the function body.</li><li>Function body: A set of statements that are executed when the function is called. If the function consists of a single expression, you can omit the curly braces <strong><em>{}</em></strong> and the <strong><em>return</em></strong><em> </em>keyword.</li></ul><pre>// Function with no parameters<br>const greet = () =&gt; console.log(&#39;Hello!&#39;);<br><br>// Function with one parameter<br>const double = x =&gt; x * 2;<br><br>// Function with multiple parameters<br>const add = (x, y) =&gt; x + y;<br><br>// Function with multiple statements in the body<br>const printMessage = (name, message) =&gt; {<br>  console.log(`${name}: ${message}`);<br>};</pre><p>Arrow functions have some differences in behavior compared to regular function expressions, such as how they handle the <strong><em>this </em></strong>keyword. However, in general, they can be used interchangeably with regular functions in most cases.</p><p><strong><em>Advantages:</em></strong></p><ul><li><em>Concise syntax</em>: Arrow functions have a more concise syntax than traditional functions, making code easier to read and write. They typically require less code and fewer characters than traditional functions, which can help reduce the potential for errors.</li><li><em>Implicit return</em>: Arrow functions automatically return the result of the expression or statement inside the function body, without the need for the <strong><em>return</em></strong> keyword. This can help reduce the amount of code needed to write a function and make the code more readable.</li><li><em>Lexical this</em>: Arrow functions capture the value of <strong><em>this</em></strong> from the surrounding scope, rather than creating their own <strong><em>this </em></strong>value. This can help reduce confusion and errors when working with <strong><em>this </em></strong>in object-oriented programming.</li><li><em>No binding of this</em>: Arrow functions do not bind their own <strong><em>this</em></strong>, so the value of <strong><em>this </em></strong>inside the function is the same as the value of <strong><em>this </em></strong>outside the function. This can help simplify code and make it easier to reason about.</li><li><em>Implicit binding of this</em>: Arrow functions inherit the <strong><em>this </em></strong>value from their lexical enclosing scope, making it easier to access the value of <strong><em>this </em></strong>from parent functions or methods.</li></ul><h4>export and import</h4><p>In JavaScript, the <strong><em>exports</em></strong> and <strong><em>imports</em></strong> statements are used to define and access modules, which are self-contained pieces of code that can be reused across multiple files and projects.</p><p><strong><em>export:</em></strong></p><p>The <strong><em>exports </em></strong>statement is used to define what parts of a module should be made available for use outside the module. It can be used to export functions, variables, and objects, as well as classes, interfaces, and other types of code.</p><pre>// math.js<br>const add = (x, y) =&gt; x + y;<br>const subtract = (x, y) =&gt; x - y;<br><br>exports.add = add;<br>exports.subtract = subtract;<br></pre><p>In this example, the <strong><em>add </em></strong>and <strong><em>subract</em></strong> functions are defined within the math.js module, and the <strong><em>exports</em></strong> statement is used to make them available for use outside the module.</p><p><strong><em>import:</em></strong></p><p>The <strong><em>imports</em></strong> statement is used to access the parts of a module that have been exported using the <strong><em>exports </em></strong>statement. It can be used to import functions, variables, and objects, as well as classes, interfaces, and other types of code.</p><pre>// app.js<br>import { add, subtract } from &#39;./math.js&#39;;<br><br>console.log(add(1, 2));      // Outputs 3<br>console.log(subtract(5, 3)); // Outputs 2</pre><p>In this example, the <strong><em>add </em></strong>and <strong><em>subract</em></strong> functions are imported from the math.js module using the <strong><em>import</em></strong> statement, and are then used within the app.js module.</p><h4>Classes</h4><p>In JavaScript, classes are a way of defining objects and their properties and behaviors in a structured and organized manner, making it easier to write and maintain complex code.</p><pre>class MyClass {<br>  constructor(param1, param2) {<br>    this.property1 = param1;<br>    this.property2 = param2;<br>  }<br><br>  method1() {<br>    // Method implementation<br>  }<br><br>  method2() {<br>    // Method implementation<br>  }<br>}</pre><p>In this example, the <em>MyClass</em> class is defined with a constructor that takes two parameters and assigns them to the class&#39;s <em>property1</em> and <em>property2</em> properties. The class also includes two methods, <em>method1</em> and <em>method2</em>, which can be called on instances of the class.</p><ul><li>To create an instance of a class, you can use the <strong><em>new</em></strong> keyword:</li></ul><pre>const myObj = new MyClass(&#39;value1&#39;, &#39;value2&#39;);</pre><p>This will create a new instance of the <em>MyClass</em> with the <em>property1</em> and <em>property2</em> properties set to <em>value1</em> and <em>value2 </em>, respectively.</p><ul><li>Classes in JavaScript can also inherit properties and behaviors from other classes using the <strong><em>extends</em></strong> keyword:</li></ul><pre>class MySubClass extends MyClass {<br>  constructor(param1, param2, param3) {<br>    super(param1, param2);<br>    this.property3 = param3;<br>  }<br><br>  method3() {<br>    // Method implementation<br>  }<br>}</pre><p>In this example, the <em>MySubClass</em> class extends the <em>MyClass</em> class and adds a new property <em>property3</em> and method <em>method3</em>. The <strong><em>super </em></strong>keyword is used to call the constructor of the parent class and pass in the <em>param1</em> and <em>param2</em> arguments. Instances of <em>MySubClass</em> will have access to the methods and properties defined in both <em>MyClass </em>and <em>MySubClass</em>.</p><h4>Spread and Rest Parameters</h4><p>In JavaScript, the spread and rest parameters are both ways of working with arrays and objects making it easier to write cleaner and more concise code.</p><p><strong><em>Spread Operator:</em></strong></p><ul><li>The spread syntax is used to “spread” the elements of an array or object into another array or object.</li><li>It is denoted by the <strong><em>…</em></strong> operator.</li></ul><pre>const arr1 = [1, 2, 3];<br>const arr2 = [4, 5, 6];<br><br>const arr3 = [...arr1, ...arr2];<br><br>console.log(arr3); // Outputs [1, 2, 3, 4, 5, 6]</pre><p>In this example, the spread syntax is used to combine the <em>arr1</em> and <em>arr2</em> arrays into a new array <em>arr3</em>.</p><ul><li>Spread syntax can also be used with objects to create a new object that combines the properties of multiple objects.</li></ul><pre>const obj1 = { a: 1, b: 2 };<br>const obj2 = { c: 3, d: 4 };<br><br>const obj3 = { ...obj1, ...obj2 };<br><br>console.log(obj3); // Outputs { a: 1, b: 2, c: 3, d: 4 }</pre><p>In this example, the spread syntax is used to combine the <em>obj1</em> and <em>obj2</em> objects into a new object<em> obj3</em>.</p><p><strong><em>Rest parameters:</em></strong></p><ul><li>The rest parameter, also denoted by the <strong><em>…</em></strong> operator, is used to represent an indefinite number of arguments as an array.</li><li>It is typically used in function definitions to handle variable-length argument lists.</li></ul><pre>function sum(...numbers) {<br>  return numbers.reduce((acc, curr) =&gt; acc + curr, 0);<br>}<br><br>console.log(sum(1, 2, 3, 4)); // Outputs 10</pre><p>In this example, the <em>sum </em>function takes an indefinite number of arguments using the rest parameter syntax. The <em>numbers </em>parameter is an array that contains all of the arguments passed to the function.</p><h4>Destructuring</h4><ul><li>Destructuring is a way to extract values from arrays and objects and assign them to variables in a more concise way.</li><li>It can be used with arrays, objects, and even nested structures.</li></ul><p><strong><em>Destructing with an array</em></strong></p><pre>const arr = [1, 2, 3];<br><br>const [a, b, c] = arr;<br><br>console.log(a); // Outputs 1<br>console.log(b); // Outputs 2<br>console.log(c); // Outputs 3</pre><p>In this example, the destructuring syntax is used to extract the values of the <em>arr </em>array and assign them to the variables <em>a</em>, <em>b</em> and <em>c</em>.</p><p><strong><em>Destructing with an object</em></strong></p><pre>const obj = { a: 1, b: 2, c: 3 };<br><br>const { a, b, c } = obj;<br><br>console.log(a); // Outputs 1<br>console.log(b); // Outputs 2<br>console.log(c); // Outputs 3</pre><p>In this example, the destructuring syntax is used to extract the values of the <em>obj</em> object&#39;s properties <em>a</em>, <em>b</em> and <em>c</em> and assign them to variables with the same names.</p><p><strong><em>Destructing with nested structures</em></strong></p><pre>const obj = { <br>  a: 1, <br>  b: { <br>    c: 2, <br>    d: 3 <br>  }<br>};<br><br>const { a, b: { c, d } } = obj;<br><br>console.log(a); // Outputs 1<br>console.log(c); // Outputs 2<br>console.log(d); // Outputs 3</pre><p>n this example, the destructuring syntax is used to extract the values of the <em>obj</em> object&#39;s properties <em>a</em>, <em>b.c</em> and <em>b.d</em> and assign them to variables with the same names.</p><h4>Template Literals</h4><ul><li>Template literals allows for easier string interpolation and multiline string formatting in JavaScript.</li><li>Instead of using the traditional single quotes or double quotes to define a string, template literals are enclosed in backticks <strong><em>(`)</em></strong>. Within a template literal, variables or expressions can be inserted using <em>${…}</em> syntax, which will be evaluated and replaced with their values at runtime.</li></ul><pre>const name = &quot;John&quot;;<br>const age = 25;<br>const message = `My name is ${name} and I am ${age} years old.`;<br>console.log(message);//My name is John and I am 25 years old.</pre><ul><li>Template literals also make it easier to create multiline strings, as they can include line breaks and indentation without needing to use escape characters or concatenation.</li></ul><pre>const multiline = `<br>  This is a<br>  multiline<br>  string.`;<br>console.log(multiline);</pre><p>This will output:</p><pre>  This is a<br>  multiline<br>  string.</pre><h4>Array functions</h4><p>Array functions are used to maintain code that involves manipulating and transforming arrays and make it easier to write concise, efficient, and maintainable code when working with arrays.</p><ul><li><strong><em>Array.from(): </em></strong>This method creates a new array from an iterable object or array-like object, such as a NodeList or a string.</li></ul><pre>const str = &#39;hello&#39;;<br>const arr = Array.from(str);<br>console.log(arr); // Output: [&#39;h&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;]</pre><ul><li><strong><em>Array.find():</em></strong> This method returns the first element in an array that satisfies a specified condition. If no element satisfies the condition, it returns undefined.</li></ul><pre>const numbers = [1, 2, 3, 4, 5];<br>const evenNumber = numbers.find(num =&gt; num % 2 === 0);<br>console.log(evenNumber); // Output: 2</pre><ul><li><strong><em>Array.findIndex():</em></strong> This method returns the index of the first element in an array that satisfies a specified condition. If no element satisfies the condition, it returns -1.</li></ul><pre>const numbers = [1, 2, 3, 4, 5];<br>const evenNumberIndex = numbers.findIndex(num =&gt; num % 2 === 0);<br>console.log(evenNumberIndex); // Output: 1</pre><ul><li><strong><em>Array.some(): </em></strong>This method returns true if at least one element in an array satisfies a specified condition, otherwise it returns false.</li></ul><pre>const numbers = [1, 2, 3, 4, 5];<br>const hasEvenNumber = numbers.some(num =&gt; num % 2 === 0);<br>console.log(hasEvenNumber); // Output: true</pre><ul><li><strong><em>Array.every():</em></strong> This method returns true if all elements in an array satisfy a specified condition, otherwise it returns false.</li></ul><pre>const numbers = [2, 4, 6, 8, 10];<br>const areAllEvenNumbers = numbers.every(num =&gt; num % 2 === 0);<br>console.log(areAllEvenNumbers); // Output: true</pre><ul><li><strong><em>Array.includes():</em></strong> This method checks whether an array includes a certain value, and returns true or false accordingly.</li></ul><pre>const numbers = [1, 2, 3, 4, 5];<br>const includesThree = numbers.includes(3);<br>console.log(includesThree); // Output: true</pre><h4>Async Code</h4><p>Async Code features make it easier to write, read, and manage asynchronous code in JavaScript, improving the reliability and performance of web applications.</p><p><strong><em>Promises:</em></strong></p><ul><li>Promises are a way to handle asynchronous operations in JavaScript.</li><li>A Promise represents a value that may not be available yet, but will be resolved at some point in the future.</li><li>Promises provide a cleaner way to handle callbacks and manage the flow of asynchronous code.</li><li>A Promise has three states:</li></ul><blockquote>Pending: The initial state of a promise. The promise is neither fulfilled nor rejected.</blockquote><blockquote>Fulfilled: The state of a promise when it is resolved successfully. The promise returns a value.</blockquote><blockquote>Rejected: The state of a promise when it fails to be resolved. The promise returns an error.</blockquote><pre>const myPromise = new Promise((resolve, reject) =&gt; {<br>  // Do some asynchronous operation<br>  setTimeout(() =&gt; {<br>    const randomNum = Math.floor(Math.random() * 10);<br>    if (randomNum &lt; 5) {<br>      resolve(randomNum); // fulfilled state<br>    } else {<br>      reject(&#39;Number is greater than or equal to 5&#39;); // rejected state<br>    }<br>  }, 1000);<br>});<br><br>myPromise<br>  .then((result) =&gt; {<br>    console.log(result); // Output: A number less than 5<br>  })<br>  .catch((error) =&gt; {<br>    console.error(error); // Output: Number is greater than or equal to 5<br>  });</pre><p>In this example, we created a new Promise that simulates an asynchronous operation by generating a random number between 0 and 9 after a 1-second delay. If the number is less than 5, the Promise is resolved with that number. If the number is greater than or equal to 5, the Promise is rejected with an error message.</p><p>We then handle the Promise using the .then() method, which is called when the Promise is fulfilled, and the .catch() method, which is called when the Promise is rejected. This allows us to easily handle the results of the Promise in a clear and concise way.</p><p><strong><em>Async/await:</em></strong></p><ul><li>The async/await syntax simplifies the use of Promises by allowing developers to write asynchronous code that looks and feels like synchronous code.</li><li>The <strong><em>async </em></strong>keyword is used to define a function as asynchronous, and the <strong><em>await </em></strong>keyword is used to wait for a Promise to resolve before continuing execution.</li></ul><pre>async function getData() {<br>  const response = await fetch(&#39;https://example.com/data&#39;);<br>  const data = await response.json();<br>  return data;<br>}<br><br>getData().then((data) =&gt; {<br>  console.log(data);<br>}).catch((error) =&gt; {<br>  console.error(error);<br>});</pre><p>This code defines an asynchronous function called getData that fetches data from a URL and returns it as JSON. The await keyword is used to wait for the Promise returned by the fetch() method to resolve before continuing to parse the JSON response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*kTBFx0KfnGH_sJG_exp3VQ.png" /><figcaption>Difference of async/await and Promise</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=327a0f10ba82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuration of Custom Application for Merchant Center Commerce tools]]></title>
            <link>https://aarthinim.medium.com/configuration-of-custom-application-for-merchant-center-commerce-tools-10fed5c97a91?source=rss-756946511e09------2</link>
            <guid isPermaLink="false">https://medium.com/p/10fed5c97a91</guid>
            <dc:creator><![CDATA[Aarthini]]></dc:creator>
            <pubDate>Thu, 14 Apr 2022 07:19:21 GMT</pubDate>
            <atom:updated>2022-04-14T07:19:21.966Z</atom:updated>
            <content:encoded><![CDATA[<h3>Custom Application for Merchant Center</h3><p>A Custom Application is a web application that is developed and self-hosted by the customer. To make the application visible and accessible in the Merchant Center, it needs to be registered for each project in the commercetools platform through the Merchant Center.</p><p>The Merchant Center provides a set of functionalities built-in and maintained by the commercetools platform team. For example managing a product catalog, orders, discounts etc. The built-in features are usually aligned with the functionalities of the commercetools platform HTTP API.</p><p>However, there are cases where a customer project requires extra functionalities that are specific to that customer’s needs. To solve some of these problems, commercetools allows you to build Custom Applications for the Merchant Center.</p><h3>Building Custom Application</h3><ol><li><strong>Develop</strong> the Custom Application : Use the tools and components to develop a Custom Application’s business logic, then use the <a href="https://uikit.commercetools.com/?path=/story/*"><em>UIKit</em></a> to give it a look and feel that’s unified with the Merchant Center.</li><li><strong>Deploy</strong> the Custom Application : When the Custom Application is ready to be used in production, deploy it to a production environment</li><li><strong>Register</strong> the Custom Application : Register the Custom Application for a project of the commercetools platform and activate it. Once a Custom Application is activated, it can be accessed from the Merchant Center’s main menu.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfAw6SJUWwyQwupjPMBdNg.png" /></figure><h3>Creating Custom Applications</h3><h4>Prerequisites</h4><ul><li>Commercetools account and project.</li><li>Node.js installed version ≥12, recommended ≥14.</li><li>Basic knowledge in react.</li></ul><p><strong>Installing a starter application</strong></p><ul><li>Install the starter application using the below command,</li></ul><pre>npx @commercetools-frontend/create-mc-app \custom_app_name\--template starter</pre><ul><li>In the <strong><em>custom-application-config.json</em></strong> file in the root folder, change the <em>cloudIdentifier </em>attribute value according to the commercetools platform regions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRh03g3IfTZqi1Mnz6qfIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*aB2cOI5v7pYLdCJrvOP-Pg.png" /></figure><ul><li>Start the development server, use the commercetools credentials to login</li></ul><pre>$ cd custom_app_name</pre><pre>$ npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dbCTL8DtRbv_krYX4XcUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-KUhJTOBLRel1COal2x2Q.png" /></figure><h3>Create a new page</h3><ul><li>Create a new page under the src/components folder, use the <a href="https://uikit.commercetools.com/?path=/story/introduction--getting-started">UI kit</a> provided by the commerce tools to make the look and feel similar to the commerce tools merchant center.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZSbo4FrQicuujMyubyBNcA.png" /></figure><ul><li>To route the page, configure the order page in the route.js file in the src folder</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbU2LNpttFxLG1m74HE5ZA.png" /></figure><ul><li>To display the page, have to configure <em>submenuLinks attribute </em>in <strong><em>custom-application-config.json</em></strong> file in the root folder, in that <em>uriPath </em>attribute value should be same as the path mentioned in the route.js file.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2x_HzTeT5FKIFKOKx-yPQA.png" /></figure><ul><li>Once all process done, restart the server, then the page will be displayed as below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_3Ei1MEcr5jKFmtXygxBA.png" /></figure><h3>Store API link globally</h3><ul><li>To store API links globally, so that we don’t have to change the link in each file manually. For this have to configure in <strong><em>custom-application-config.json</em></strong> file in the root folder,</li></ul><pre>  additionalEnv:{<br>      externalApiUrl: &#39;https://my-custom-app.com/graphql&#39;<br>  } </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRTveesn24zoHN-4NRWwsw.png" /></figure><ul><li>we can access the <em>externalApiUrl </em>value using below code,</li></ul><pre>import { useApplicationContext } from &#39;@commercetools-frontend/application-shell-connectors&#39;;<br>const externalApiUrl = useApplicationContext(context =&gt; context.environment.externalApiUrl);</pre><h3>Proxy to External API</h3><p>Merchant Center applications can make authenticated requests using the proxy endpoints to the underlying APIs that are configured and supported for the Merchant Center. Requests are authenticated via the mcAcessToken stored in a secure cookie, which is set only for commercetools.com domains.</p><p>To validate that the request comes from an authenticated user, the Merchant Center API Gateway provides an endpoint that must be used to connect to your external API in a secured manner.</p><ul><li><strong><em>/proxy/forward-to</em></strong></li></ul><p>Requests to that endpoint should additionally pass the following HTTP headers:</p><ul><li><strong><em>Accept-version</em></strong>: v2</li><li><strong><em>X-Forward-To</em></strong><em>: &lt;url&gt;</em>: The URL to your external API.</li><li><strong><em>X-Project-Key</em></strong>: &lt;project-key&gt;: The key of the project currently being used by the Custom Application. The Merchant Center API Gateway will perform a validation check to ensure that the user has access to the project, then forward the request to your server only if the check was successful.</li></ul><p>To facilitate the usage, there are two ways,</p><ul><li>Usage for Apollo</li><li>Usage for SDK actions</li></ul><h4>Usage for Apollo</h4><p>Commerce tools Merchant center provides the context option for Apollo queries to adjust how request is configured and executed. The <em>@commercetools-frontend/application-shell</em> package now exposes an utility function to configure the Apollo context for the <em>/proxy/forward-to</em> usage.</p><pre>import React from &#39;react&#39;;<br>import {createApolloContextForProxyForwardTo,useMcQuery} from &#39;@commercetools-frontend/application-shell&#39;;<br>import { useApplicationContext } from &#39;@commercetools-frontend/application-shell-connectors&#39;;</pre><pre>const Customer = (props) =&gt; {<br>const externalApiUrl = useApplicationContext(context =&gt; context.environment.externalApiUrl);</pre><pre>const { loading, data, error } = useMcQuery(MyQuery, {<br>context: createApolloContextForProxyForwardTo({<br>  uri: externalApiUrl,<br>  headers: {<br>   &#39;x-foo&#39;: &#39;bar&#39;,<br>  },<br>  }),<br>});</pre><pre>return (<br>&lt;Text.Body&gt;{&quot;Custom application&quot;}&lt;/Text.Body&gt;<br>)<br>}</pre><h4>Usage for SDK actions</h4><p>By default SDK actions are configured in the merchant center, they can be used as below</p><pre>actions.forwardTo.get({ uri: &#39;https://my-custom-app.com/graphql&#39; });</pre><pre>actions.forwardTo.del({ uri: &#39;https://my-custom-app.com/graphql&#39; });</pre><pre>actions.forwardTo.head({ uri: &#39;https://my-custom-app.com/graphql&#39; });</pre><pre>actions.forwardTo.post({uri: &#39;https://my-custom-app.com/graphql&#39;,<br>payload: { say: &#39;Hello&#39; },<br>});</pre><pre>actions.forwardTo.get({uri: &#39;https://my-custom-app.com/graphql&#39;,<br>headers: {<br>&#39;x-foo&#39;: &#39;bar&#39;,<br>},<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_gp40GHGep55OLSnMZFig.png" /></figure><h3>Data Fetching</h3><ul><li>Requests to GraphQL API.</li><li>Requests to REST API.</li></ul><h4>Requests to GraphQL API</h4><p>With this we can fetch the data using the GraphQL query.</p><p>Create a .graphql file</p><p>In the below example, we query for a products (products.gaphql).</p><pre>query fetchProducts{<br>products{<br> results{<br> id<br> version<br> productType{<br>  name<br>  }<br> }<br> }<br>}</pre><p>In custom application, to fetch data using the graphql query</p><pre>import React from &#39;react&#39;;</pre><pre>import { Query } from &#39;@apollo/client/react/components&#39;;</pre><pre>import Text from &#39;@commercetools-uikit/text&#39;;</pre><pre>import { GRAPHQL_TARGETS } from &#39;@commercetools-frontend/constants&#39;;</pre><pre>import { fetchProducts} from &#39;./products.graphql&#39;;</pre><pre>const target = GRAPHQL_TARGETS.COMMERCETOOLS_PLATFORM;</pre><pre>const Products= props =&gt; (<br>&lt;Query<br><em>query</em>={fetchProducts}<br><em>context</em>={{ target }}<br>&gt;<br>{({ loading, error, data }) =&gt; {<br>if (loading) return &#39;Loading...&#39;;<br>if (error) return `Error! ${error.message}`;<br>return (</pre><pre>data.forEach(item=&gt;{<br>&lt;Text.Headline <em>as</em>=&quot;h1&quot;&gt;{`Product: ${item.product.name}`}&lt;/Text.Headline&gt;})<br>);<br>}}<br>&lt;/Query&gt;<br>);</pre><pre>export default Products;</pre><h4>Requests to REST API</h4><p>We can request the data using commercetools inbuilt <em>sdkActions</em></p><p>Create a action.js</p><pre><em>// actions.js</em></pre><pre>import { actions as sdkActions } from &#39;@commercetools-frontend/sdk&#39;;<br>import { MC_API_PROXY_TARGETS } from &#39;@commercetools-frontend/constants&#39;;</pre><pre>const fetchProductByKey = key=&gt;<br>sdkActions.get({<br>mcApiProxyTarget: MC_API_PROXY_TARGETS.COMMERCETOOLS_PLATFORM,<br>service: &#39;products&#39;,<br>options: {key},<br>});</pre><pre><em>// channel-details.js</em></pre><pre>import React from &#39;react&#39;;</pre><pre>import Text from &#39;@commercetools-uikit/text&#39;;</pre><pre>import { useAsyncDispatch } from &#39;@commercetools-frontend/sdk&#39;;</pre><pre>import { useShowApiErrorNotification } from &#39;@commercetools-frontend/actions-global&#39;;<br>import * as actions from &#39;./actions&#39;;</pre><pre>const initialState = {<br> isLoading: true,<br> data: null,<br> error: null,<br>};</pre><pre>const reducer = (state = initialState, action) =&gt; {<br>switch (action.type) {<br> case &#39;ok&#39;:<br>   return { isLoading: false, data: action.payload, error: null };<br> case &#39;error&#39;:<br>   return { isLoading: false, data: null, error: action.payload };<br>default:return state;<br>}};</pre><pre>const Products= props =&gt; {<br> const asyncDispatch = useAsyncDispatch();<br> const showApiErrorNotification = useShowApiErrorNotification();<br> const [state, dispatch] = React.useReducer(reducer, initialState);<br> React.useEffect(() =&gt; {<br>  asyncDispatch(<br>    actions.fetchProductByKey(props.key)<br>  ).then(result =&gt; {<br>  dispatch({ type: &#39;ok&#39;, payload: result });<br>  }).catch(error =&gt; {<br>  dispatch({ type: &#39;error&#39;, payload: error });<br>  showApiErrorNotification({ errors: error });<br>  })}, [props.key, asyncDispatch]);<br>  if (state.isLoading) return &#39;Loading...&#39;;<br>  if (state.error) return `Error! ${state.error.message}`;<br>  return &lt;Text.Headline <em>as</em>=&quot;h1&quot;&gt;{`Product: ${state.data.name}`}     &lt;/Text.Headline&gt;;<br> };</pre><pre>export default Products;</pre><h4>Using file uploads</h4><p>If we are using the file uploads we need to use the FormData</p><p>The FormData object can then be sent as the request HTTP body.</p><p>It is important to properly configure the <em>Content-Type</em> HTTP header, which usually must be set to <em>multipart/form-data</em>. However, you also need to provide a boundary directive.</p><p>Its recommend to omit the <em>Content-Type</em> HTTP header in the request and let the browser correctly infer it.</p><pre>When using the @commercetools-frontend/sdkpackage, need to explicitly unset the Content-Type HTTP header by passing null as value</pre><pre>{<br>  &#39;Content-Type&#39;: null<br>}</pre><h4>Conclusion</h4><p>Configurations and the data fetching techniques included in the blog for setting up the basic custom application for the commerce tools.</p><p>For deployments refer <a href="https://docs.commercetools.com/custom-applications/deployment-examples">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10fed5c97a91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vuex in Vue.js]]></title>
            <link>https://aarthinim.medium.com/vuex-in-vue-js-c5027bf7b2b4?source=rss-756946511e09------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5027bf7b2b4</guid>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Aarthini]]></dc:creator>
            <pubDate>Thu, 09 Sep 2021 10:57:06 GMT</pubDate>
            <atom:updated>2021-09-09T10:57:06.844Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Vuex</strong></h3><p>Vuex is Vue’s own state management pattern and library. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated predictably. It also integrates with Vue’s official dev tools extension to provide advanced features such as zero-config time-travel debugging and state snapshot export/import. Vuex implements the Flux pattern the same way that other frameworks implement the MVC pattern. Vuex keeps your application data in a transparent and predictable state even when that data is being shared across multiple components.</p><h3><strong>Realtime Example</strong></h3><p>Imagine you’ve developed a multi-user chat app. The interface has a user list, private chat windows, an inbox with chat history, and a notification bar to inform users of unread messages from other users they aren’t currently viewing.</p><p>Millions of users are chatting to millions of other users through your app daily. However, there are complaints about an annoying problem: the notification bar will occasionally give false notifications. A user will be notified of a new unread message, but when they check to see what it is it’s just a message they’ve already seen. To avoid the scenario we can use vuex.</p><h3><strong>Vuex-State Management Pattern</strong></h3><ul><li><strong>State: </strong>the source of truth that drives the app.</li><li><strong>View: </strong>a declarative mapping of the <em>state</em>.</li><li><strong>Actions: </strong>the possible ways the state could change in reaction to user inputs from the <em>view</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ljHin04KyRrLq5Oo7qJOXw.jpeg" /><figcaption>State management flow</figcaption></figure><h3><strong>Installation</strong></h3><p>Install the library using the below command</p><p><strong>NPM</strong></p><pre>npm install vuex --save</pre><p><strong>Yarn</strong></p><pre>yarn add vuex</pre><h3><strong>Creating a Vuex store</strong></h3><p>To create Vuex store. To do this, create a JavaScript module file at <em>src/store/index.js</em>.</p><pre>$ mkdir src/store <br>$ touch src/store/index.js</pre><p>Open the src/store/index.js file and import the <em>createStore </em>method. This method is used to define the store and its features. For now, export the store so it can easily be added to our Vue app.</p><pre>import { createStore } from &quot;vuex&quot;;  <br>export default createStore({});</pre><h3>Adding the store to a Vue instance</h3><p>To ensure the access of Vuex store from within any component, need to import the store module in the main file, and install the store as a plugin on the main Vue instance</p><pre>import { createApp } from &quot;vue&quot;; <br>import App from &quot;@/App&quot;; <br>import store from &quot;@/store&quot;; </pre><pre>const app = createApp(App); <br>app.use(store); <br>app.mount(&quot;#app&quot;);</pre><h3>Vuex store in App</h3><p><strong>Creating vuex store</strong></p><p>Create a JavaScript module file at <em>src/store/index.js</em>.</p><p>In the <strong><em>src/store/index.js</em></strong><em> </em>file import the createStore method</p><pre>import { createStore } from &quot;vuex&quot;;  <br>export default createStore({});</pre><p><strong>Adding the store to a Vue instance</strong></p><p>To access the vuex store in any components, import the store in the main file(<strong><em>src/main.js</em></strong>).</p><pre>import { createApp } from &quot;vue&quot;; <br>import App from &quot;@/App&quot;; <br>import store from &quot;@/store&quot;;  <br>const app = createApp(App);  <br>app.use(store); <br>app.mount(&quot;#app&quot;);</pre><h3>Code Sample</h3><h4>Create a sample app using vuex</h4><p>To create a new vuejs app, use the below command</p><pre>$ vue create vuex-example</pre><h4>Creating a component Todo</h4><p>Create a new component Todo in the folder<strong><em> src/components/Todo.vue </em></strong>that displays to-do items</p><pre>&lt;template&gt;  <br>  &lt;form @submit.prevent=&quot;addTodo&quot;&gt;    <br>  &lt;input type=&quot;text&quot; placeholder=&quot;Enter a new task&quot; v-model=&quot;task&quot;/&gt;  <br>  &lt;/form&gt; <br>&lt;/template&gt;<br>&lt;script&gt; <br>export default {  <br> data() {    <br>   return {      <br>    task: &quot;&quot;,       <br>    id: 0    <br>  };   }, <br> methods: {   <br>  addTodo: function() {  <br>     //     <br>  }   <br> }  }; <br>&lt;/script&gt;</pre><h4>Defining Store state</h4><p>Todo component need to access the same data, this will be the perfect for global <em>state </em>which will hold in Vuex store.</p><p>Create vuex store in the <strong><em>src/store/index.js</em></strong></p><pre>import { createStore } from &quot;vuex&quot;; <br> export default createStore({ <br>  state () {   <br>   return {   <br>    todos: [] <br>    } <br>  }<br> });</pre><h4>Defining mutations</h4><p>Vuex state cannot be directly mutated, for that need to define <em>mutator</em> functions. For this add a mutations property to the store and add a function property addTodo.</p><p>All mutators receive the store state as their first argument. The second optional argument is the data that components calling the mutator can pass in.</p><p>In the function body, let’s use the unshift method to add the new to-do item to the top of the todo array list.</p><pre>import { createStore } from &quot;vuex&quot;;              <strong>src/store/index.js</strong><br> export default createStore({ <br>  state () {<br>     return { <br>      todos: []<br>     }<br>   },<br>   mutations: {<br>     addTodo (state, item) {<br>       state.todos.unshift(item);<br>     }<br>   }<br> });</pre><h4>Using mutations-commits</h4><p>To access the store we can use the global property <em>this.$store. U</em>se the <em>commit </em>method to create a new mutation, it passed two arguments - first argument, the name of the mutation, and second argument, the object we want to pass, ie., new to-do item</p><pre>methods: {                                   <strong>src/components/Todo.vue</strong>                                    <br>   addTodo: function() {<br>     const { id, task } = this;<br>     this.$store.commit(&quot;addTodo&quot;, { id, task });<br>     this.id++;<br>     this.task = &quot;&quot;;<br>   }<br> }</pre><h4>Review the component Todo</h4><pre>&lt;template&gt;<br>   &lt;form @submit.prevent=&quot;addTodo&quot;&gt;<br>   &lt;input type=&quot;text&quot; placeholder=&quot;Enter a new task&quot; v-model=&quot;task&quot;      /&gt;         <br>   &lt;/form&gt;<br> &lt;/template&gt;<br>&lt;script&gt;<br>export default {<br>   data() {<br>     return {<br>       task: &quot;&quot;,<br>       id: 0<br>     };<br>   },<br>  methods: {<br>     addTodo: function() {<br>       const { id, task } = this;<br>       this.$store.commit(&quot;addTodo&quot;, { id, task });<br>       this.id++;<br>       this.task = &quot;&quot;;<br>     }<br>   }<br> };<br> &lt;/script&gt;</pre><h4>Reading store data</h4><p>create a new component <em>TodoList, to display the todo items</em></p><pre>&lt;template&gt;<br> &lt;ul&gt;<br>   &lt;li v-for=&quot;todo in todos&quot; :key=&quot;todo.id&quot;&gt;{{ todo.description }}     &lt;/li&gt;<br> &lt;/ul&gt;<br> &lt;/template&gt;<br>&lt;script&gt;<br> export default {<br>   computed: {<br>     todos() {<br>       //      <br>    }<br>   }<br> };<br> &lt;/script&gt;</pre><h4>Defining getters</h4><p>Rather than accessing the store content directly, <em>getters </em>are functions that are like computed properties for the store. These are perfect for filtering or transforming data before returning it to the app.</p><p>For example, below we have <em>getTodos </em>which returns the state unfiltered. In many scenarios, you may transform this content with a <em>filter </em>or <em>map</em>.</p><p><em>todoCount </em>returns the length of the todo array.</p><pre>export default createStore({                      <strong>src/store/index.js</strong><br>  state () {<br>     return { <br>      todos: []<br>     }<br>   },<br>   mutations: {<br>     addTodo (state, item) {<br>       state.todos.unshift(item);<br>     }<br>   }<br>   getters: {<br>     getTodos (state) {<br>       return state.todos;<br>     },<br>     todoCount (state) {<br>       return state.todos.length;<br>     }<br>   }<br> })</pre><p>TodoList component, complete the functionality by returning this.$store.getters.getTodos.</p><pre>&lt;script&gt;                                 <strong>src/components/TodoList.vue</strong><br> export default {<br>   computed: {<br>     todos() {<br>       return this.$store.getters.getTodos;<br>     }<br>   }<br> };<br> &lt;/script&gt;</pre><h3>App.vue</h3><p>To complete the app, all there is to do now is import and declare components in <em>App.vue</em>.</p><pre>&lt;template&gt;<br>   &lt;div&gt;<br>     &lt;h1&gt;To-Do List&lt;/h1&gt;<br>   &lt;div&gt;<br>   &lt;Todo/&gt;<br>   &lt;TodoList /&gt;<br>&lt;/template&gt;<br>&lt;script&gt;<br>import Todo from &quot;@/components/Todo.vue&quot;;<br>import TodoList from &quot;@/components/TodoList.vue&quot;;<br>export default {<br>   components: {<br>     TodoNew,<br>     TodoList<br>   }<br> };<br> &lt;/script&gt;</pre><h3><strong>Conclusion</strong></h3><p>Vuex is used in a large application, having a global state management solution is going to help keep the app predictable and maintainable.</p><p><strong>Pros of Vuex:</strong></p><ul><li>Easy management of global state</li><li>Powerful debugging of global state</li></ul><p><strong>Cons of Vuex:</strong></p><ul><li>An additional project dependency</li><li>Verbose boilerplate</li></ul><p>One possible alternative in Vue 3 is to roll own Vuex using the Composition API. It doesn’t give you the debugging capabilities of Vuex, but it’s a lightweight alternative that may work in small projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5027bf7b2b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PubSub in ReactJs]]></title>
            <link>https://aarthinim.medium.com/pubsub-in-reactjs-eaa8f9d6ec0?source=rss-756946511e09------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaa8f9d6ec0</guid>
            <category><![CDATA[pub-sub]]></category>
            <dc:creator><![CDATA[Aarthini]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 08:56:49 GMT</pubDate>
            <atom:updated>2021-05-19T07:07:36.678Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>PubSub js is a topic-based publish/subscribe event library written in javascript. PubSub as messaging-oriented middleware or event ingestion. PubSub js has synchronization decoupling, so topics are published asynchronously.</p><p>There are several ways for components to communicate with one another in React; each having its pros and cons. We can pass props from parent to child, or use the new Context API to pass information from parents to grandchildren while skipping the children components themselves. We can even use in-memory caching/stores, with the help of higher-order components (HOC), to update data and trigger changes in the target components.</p><p>For example, I wanted to have an alert in the main App component of my application and allow any of my other components to publish messages which the App would just, somehow, know how to handle. All of that without adding clutter to my cache or chaining through components to get back to the parent App component, PubSub can be used.</p><p>Real-time example PubSub can be used in chat applications. In the chat app, participants can subscribe to chat rooms that have a designated PubSub topic. When a user sends a message to a chat room, the chat app instance publishes the message on that chat room’s topic. Subscribers of the topic receive the message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*U79SQEsZvn4rEIEfNaX1hA.jpeg" /></figure><h3>Features</h3><ul><li>Dependency free</li><li>Possibility to publish async events</li><li>Synchronization decoupling</li><li>Easy to understand and use</li><li>Works also on IE 6+</li><li>ES3 compatible. PubSubJS should be able to run everywhere that can execute JavaScript. Browsers, servers, ebook readers, old phones, game consoles.</li></ul><h3><strong>Core Concepts</strong></h3><p><strong>Topic</strong>: A named resource that is sent by the publisher.</p><p><strong>Message: </strong>The combination of data and (optional) attributes that a publisher sends to a topic and is eventually delivered to subscribers.</p><p><strong>Publisher: </strong>This is an entity that creates and broadcasts a message to subscribers to services on a topic.</p><p><strong>Subscriber:</strong> This is an entity that is set on course to receive a message from a particular topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKhXyX0BZkB74YDY6nTGUg.png" /><figcaption>Core Concepts Flow</figcaption></figure><h3><strong>Installation</strong></h3><p>Install the library using the below command</p><p><em>npm i pubsub-js</em></p><p><strong>Flow Diagram</strong></p><p>The publisher publishes the data with the topic.</p><p>The subscriber subscribes to the topic and retrieves the data using the function.</p><p><strong>Code Sample</strong></p><p><strong><em>Code in the publisher component</em></strong></p><p>import React from ‘react’;<br> import PubSub from ‘pubsub-js’;</p><p>class PublishComponent extends React.Component{<br> publishTopic=()=&gt;{<br> let msg={“data”:”Message from Publisher”}<br> PubSub.publish(“topic1”,msg);<br> }<br> render(){<br> return(<br> &lt;div&gt;<br> &lt;button onClick={this.publishTopic}&gt;Publish&lt;/button&gt;<br> &lt;/div&gt;<br> )<br> }<br> }</p><p><strong>Publish the topic synchronously</strong></p><p>import PubSub from ‘pubsub-js’;</p><p>publishTopic=()=&gt;{<br> let msg={“data”:”Pubsub message”}<br> PubSub.publishSync(“topic1”,msg);<br> }</p><p><strong><em>Code in the subscriber component</em></strong></p><p>import React from ‘react’;<br> import PubSub from ‘pubsub-js’;</p><p>class SubscriberClass extends React.Component{</p><p>constructor(props){<br> super(props);<br> this.state={<br> labelvalue:””<br> }<br> }</p><p>componentDidMount(){<br> PubSub.subscribe(“topic1”,subscribeMethod);<br> }</p><p>subscribeMethod=(topic,msg)=&gt;{<br> this.setState({<br> labelvalue:msg.data<br> })<br> }</p><p>render(){<br> &lt;div&gt;<br> &lt;label&gt;{this.state.labelvalue}&lt;/label&gt;<br> &lt;/div&gt;<br> }<br> }</p><p>export default SubscriberClass;</p><p>For functional component subscriber event used in useEffect</p><p>useEffect(()=&gt;{<br> PubSub.subscribe(“topic1”,subscribeMethod);<br> }<br> )</p><p><strong>Cancel Specific subscription</strong></p><p>import React from ‘react’;<br> import PubSub from ‘pubsub-js’;</p><p>class SubscriberClass extends React.Component{</p><p>constructor(props){<br> super(props);<br> this.subscriberevent=null;<br> this.state={<br> labelvalue:””<br> } <br> }</p><p>componentDidMount(){<br> this.subscriberevent=PubSub.subscribe(“topic1”,subscribeMethod);<br> }</p><p>subscribeMethod=(topic,msg)=&gt;{<br> this.setState({<br> labelvalue:msg.data<br> })<br> }</p><p>render(){<br> &lt;div&gt;<br> &lt;label&gt;{this.state.labelvalue}&lt;/label&gt;<br> &lt;/div&gt;<br> }</p><p>componentWillUnMount(){<br> Pubsub.unsubscribe(this.subscriberevent);<br> }<br> }</p><p>export default SubscriberClass;</p><p><strong>Cancel All Subscription</strong></p><p>In ComponentWillUnmount method have to use the code</p><p>PubSub.clearAllSubscriptions();</p><p><strong>Error Handling</strong></p><p>//Code in Publisher component<br> var isPublished = PubSub.publish(‘topic1’,’a’);<br> <br> //Code in Subscriber component<br> var token = PubSub.subscribe(‘topic1’, mySubscriber);</p><p>In the above example, isPublished is a boolean that represents if any subscribers were registered for this topic. In the subscriber component, the token will be false if something went wrong and the subscriber was not registered.</p><p><strong>Conclusion</strong></p><p>Pubsub helps someone in need of a clean effective solution for inter-component communication without the toil of passing props or dealing with stores such as Redux or MobX. For a real-time application like a chat-based application, pubsub is the best and easiest way to achieve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaa8f9d6ec0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>