<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Famini-ProDev</title>
    <description>The latest articles on DEV Community by Famini-ProDev (@faminiprodev).</description>
    <link>https://dev.to/faminiprodev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F806704%2F1ce1c561-1eb5-4bf4-be74-bacda068a8b2.png</url>
      <title>DEV Community: Famini-ProDev</title>
      <link>https://dev.to/faminiprodev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/faminiprodev"/>
    <language>en</language>
    <item>
      <title>Testing with Jest</title>
      <dc:creator>Famini-ProDev</dc:creator>
      <pubDate>Sat, 23 Apr 2022 12:41:43 +0000</pubDate>
      <link>https://dev.to/faminiprodev/testing-with-jest-4gn3</link>
      <guid>https://dev.to/faminiprodev/testing-with-jest-4gn3</guid>
      <description>&lt;p&gt;Jest is a Javascript Testing Framework by Facebook. It is used most commonly for unit testing. Unit testing is when you provide input to a unit of code(usually, a function) and match the output with the expected output.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jest Features:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;zero config: As we will see later in this article, close to none configuration is required to get started with writing tests and deploying them. However, a config file can be supplied to the test suite as well.&lt;/li&gt;
&lt;li&gt;snapshots: Jest has the ability to enable snapshot testing as well. Essentially, the snapshots are matched with the saved snapshot and check for matching functionality.&lt;/li&gt;
&lt;li&gt;isolated tests: Jest tests are run parallelly to improve run time.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Setting up a jest project&lt;/p&gt;

&lt;p&gt;&lt;code&gt;- Install Jest using npm&lt;/code&gt;&lt;br&gt;
:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_2WN7b25--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x8d51r9lc8c99p6o4oau.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_2WN7b25--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x8d51r9lc8c99p6o4oau.png" alt="Image description" width="576" height="244"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Project Structure: &lt;/strong&gt;&lt;br&gt;
In the project root directory, make a tests folder. This folder will store all the test files. &lt;br&gt;
Note that the js files(which are to be tested) are mapped by their names. &lt;br&gt;
For example, index.js is mapped to index.test.js. This index.test.js file is placed in the 'tests' folder. This is the conventional project structure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Start testing:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To start, lets see a basic test workflow.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Hid5YLGy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/72bk37cyf8lfu1qj0q47.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Hid5YLGy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/72bk37cyf8lfu1qj0q47.png" alt="Image description" width="404" height="194"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To run the test, use the script&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will look for the test script mentioned in the package.json of the project.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JmxhW2wd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rmstjo2qxe8fkez0j1z3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JmxhW2wd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rmstjo2qxe8fkez0j1z3.png" alt="Image description" width="228" height="290"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We will use the '&lt;strong&gt;expect&lt;/strong&gt;' method to test our functions. The functions can also be tested using '&lt;strong&gt;describe&lt;/strong&gt;' and 'it'.&lt;br&gt;
A basic test: adding two positive nums and checking result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
//index.js
testForAdd: (a, b) =&amp;gt; { return (a + b) },
//index.test.js
test('test adding two positive nums', function() {
    expect(testFns.testForAdd(4, 5)).toBe(9);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the '&lt;code&gt;npm run test&lt;/code&gt;' is run, the index.test.js file is gone through. Then the &lt;em&gt;testForAdd _function is run which is placed in the '_testFns&lt;/em&gt;' object. The toBe is used to 'match' the returned response from the test to what is expected. This 'result matching' leads to either a '&lt;strong&gt;fail&lt;/strong&gt;' or a '&lt;strong&gt;pass&lt;/strong&gt;'.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--k3_CIprM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pjfuke7rg4r7p3a3muw4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--k3_CIprM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pjfuke7rg4r7p3a3muw4.png" alt="Image description" width="404" height="194"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The following test will fail because of the 'toBe(8)'.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//example of a failing test
 test('test adding two positive nums - failing test', function() {
     expect(testFns.testForAdd(4, 5)).toBe(8);
 });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Opposite of toBe&lt;/strong&gt;: &lt;em&gt;not.toBe() &lt;/em&gt;&lt;br&gt;
The opposite of the 'toBe' matcher is created by simply prefixing it with 'not.' &lt;br&gt;
For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
//test successful - test for opposite of a matcher.
//The following test will 'Pass' if the returned value is not equal to 8.
test('test adding two positive nums - failing test', function() {
    expect(testFns.testForAdd(4, 5)).not.toBe(8);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using 'toBe' with JS Objects: &lt;br&gt;
Let's think of a case where every field of a JS object is to be tested. Jest provides us a way to do this using 'toEqual'. The 'toEqual' is a deep-matcher(checks every field and sub-fields possible).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//expect toEqual example - check every field's value
// testFns.test_toEqual(gfgObj)
test('check gfgObj toEqual', () =&amp;gt; {
    let gfgObj = { name: "GFG" };
    gfgObj['type'] = "company";
    expect(gfgObj).toEqual({ name: "GFG", type: "company" });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Running the above test will '&lt;strong&gt;Pass&lt;/strong&gt;'.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--R-WpxakY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79ffdq9rtl3uyjthouzv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--R-WpxakY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79ffdq9rtl3uyjthouzv.png" alt="Image description" width="378" height="204"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Another variation of doing this is matching two objects using the '&lt;code&gt;toEqual&lt;/code&gt;'. &lt;br&gt;
This is done so like this :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test('check gfgObj toEqual', () =&amp;gt; {
    let gfgObj = {
        name: "GFG",
        type: "company",
        members: {
            employees: 100,
            contributors: 500
        }
    };
    let testObj = {
        name: "GFG",
        type: "company",
        members: {
            employees: 100,
            contributors: 500
        }
    };
    expect(gfgObj).toEqual(testObj);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This test demonstrates the deep-matching feature of toEqual. &lt;br&gt;
The above test passes as every key-pair in gfgObj matches with testObj.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7vc4PY1q--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbap2xmdqqdo111yb5qc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7vc4PY1q--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbap2xmdqqdo111yb5qc.png" alt="Image description" width="397" height="246"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;toBeCloseTo - for floating point numbers and other approximate matches *&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//see here that a+b != c even though simple addition is taking place.
&amp;gt; var a = 1.32
&amp;gt; undefined
&amp;gt; var b = 2.31
&amp;gt; undefined
&amp;gt; c = a+b;
&amp;gt; 3.63
&amp;gt; var res = false;
&amp;gt; if(c==(a+b)) {c=true;}
&amp;gt; undefined
&amp;gt; c
&amp;gt; false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In such conditions, it is good to use '&lt;code&gt;toBeCloseTo&lt;/code&gt;' matcher from the Jest library.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test('floating point number - use toBeCloseTo instead', function() {
    // const num1 = 0.3;
    // const num2 = 0.2;
    const result = 9.31 + 9.2;
    expect(result).toBeCloseTo(18.51);
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above test passes too.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;matching truthy and falsy: &lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://jestjs.io/docs/en/using-matchers#truthiness%C2%A0"&gt;https://jestjs.io/docs/en/using-matchers#truthiness &lt;/a&gt;&lt;br&gt;
A lot of times, tests are written to check for truthy and falsy values returned by 'expect'. &lt;br&gt;
**Falsy **values in JS. &lt;br&gt;
**Truthy **values in JS.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//checking for truthy values - All the tests will return truthy.

test('check for truthy', function() {
    const gfgObj = {
        first: null,
        second: undefined,
        third: false
    }
    expect(gfgObj.first).not.toBeTruthy(); // True - Pass
    expect(gfgObj.second).toBeUndefined(); // True - Pass
    expect(gfgObj.third).toBeFalsy();      // True - Pass
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above test passes.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cx7ublQu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r4e6j0nxmxrn1kxixg53.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cx7ublQu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r4e6j0nxmxrn1kxixg53.png" alt="Image description" width="341" height="134"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However, if any of the '&lt;strong&gt;expect&lt;/strong&gt;' above fails, Jest returns **meaningful **error **messages **like below.&lt;br&gt;
**Note **that in above case, if any of the 'expect'-s fail, the test also completely fails.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_DrRljis--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ycqkxekv63kai39m3pc0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_DrRljis--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ycqkxekv63kai39m3pc0.png" alt="Image description" width="398" height="325"&gt;&lt;/a&gt;&lt;br&gt;
** Matching Numbers:**&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//tests for Number matches
test('test for numbers', function() {
    const result = 3 + 9;
    // expect(result).toBe(12); //the plain old matcher
    expect(result).not.toBeLessThan(10); // result &amp;gt; 10
    expect(result).toBeLessThan(15);  // result &amp;lt; 15
    expect(result).not.toBeGreaterThan(15); // result  10
    expect(result).toBeGreaterThanOrEqual(12);  //result &amp;gt;= 12
    // expect(result).not.toBeGreaterThanOrEqual(12); // result == 12, this Fails
    // expect(result).toBeLessThanOrEqual(10); // result &amp;gt;= 10, this Fails
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gMr4Lh5J--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1hutr8bcgb94iaddkafz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gMr4Lh5J--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1hutr8bcgb94iaddkafz.png" alt="Image description" width="421" height="134"&gt;&lt;/a&gt;&lt;br&gt;
** &lt;br&gt;
Testing values contained in arrays: **&lt;/p&gt;

&lt;p&gt;We can also test if particular values are contained in an array. Note that this test will 'Fail' if at least one value is not present in the array. For example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//testing arrays
const gfgUsers = [
    'user1',
    'user2',
    'user3'
];
test('test for a value in gfgUsers', function() {
    // expect(gfgUsers).toContain('user2');
    // expect(gfgUsers).not.toContain('user2');
    //expect array containing
     expect(gfgUsers).toEqual(expect.arrayContaining(['user1', 'user3']));
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Th above test passes as user1 and user3 are present in gfgUsers.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ovuO5nP4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3nzf2nb03yfzy0i1akix.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ovuO5nP4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3nzf2nb03yfzy0i1akix.png" alt="Image description" width="399" height="130"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However, the following test will fail because 'user4' is not present in gfgUsers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//testing arrays
const gfgUsers = [
    'user1',
    'user2',
    'user3'
];
test('test for a value in gfgUsers', function() {
    //expect array containing
     expect(gfgUsers).toEqual(expect.arrayContaining(['user1', 'user4']));
}) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--o9sn-OSc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dxbgjv2ele1dmfrs3mk0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o9sn-OSc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dxbgjv2ele1dmfrs3mk0.png" alt="Image description" width="561" height="342"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test('string match tests - toMatch - used for regex-es', function() {
    const str = 'GeeksforGeeks';
    // expect(str).toMatch(/f/);
    // expect(str).toMatch(/Z/);
    //you can create more complex Regexes
    const str1 = 'This is a test paragraph. I wrote it.'
    expect(str1).toMatch(/[pP][hH][\.]/);  //matches 'ph.' in the word 'paragraph'
}) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wFQXUHWm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t71phxztyxd1sbrpa4hx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wFQXUHWm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t71phxztyxd1sbrpa4hx.png" alt="Image description" width="421" height="134"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Extending the Matchers &lt;/strong&gt;&lt;br&gt;
Jest also has the provision to extend its 'Matchers' functionality, which is accomplished using the &lt;code&gt;'expect.extend()'&lt;/code&gt; keyword. The .extend() function is passed matchers as objects. &lt;br&gt;
&lt;strong&gt;Syntax&lt;/strong&gt;: &lt;code&gt;expect.extend({matcher1, matcher2})&lt;/code&gt; ; &lt;br&gt;
For example, if we want to build a matcher that checks for a phrase presence in a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;expect.extend({
stringPresent(receivedString, phraseString) {
bool phrasePresent = true;
var re = new RegExp(phraseString);
if (re.test(receivedString)) {
    phrasePresent = true;
} else {
    phrasePresent = false;
}
if (phrasePresent === true) {
      return {
        message: () =&amp;gt;
          `string present`,
        pass: true,
      };
    } else {
      return {
        message: () =&amp;gt;
          `string absent`,
        pass: false,
      };
    }
},
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Dealing with exceptions&lt;/strong&gt; &lt;br&gt;
We can also check the types of errors that a unit of code throws. We can check the error thrown by name, message, object, etc.&lt;br&gt;
&lt;strong&gt;Syntax:expect&lt;/strong&gt;&lt;code&gt;( fnName() ).toThrow( error )&lt;/code&gt;; &lt;br&gt;
The error parameter/argument is optional here.&lt;br&gt;
Let's suppose that we want to test a function by the message of the error thrown.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function testGFGMessage() {
  throw new Error('this is testGFGMessage function error');
}
test('testing testGFGMessage', function(){
  expect(testGFGMessage).toThrow('this is testGFGMessage function error');
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are many other ways to throw Errors and check for them. A detailed reference can be found here.&lt;br&gt;
Skipping/Running a subset of tests &lt;br&gt;
&lt;a href="https://jestjs.io/docs/en/api#testskipname-fn%C2%A0"&gt;https://jestjs.io/docs/en/api#testskipname-fn &lt;/a&gt;&lt;br&gt;
Jest also has a provision for skipping specific tests while running the test suite. &lt;br&gt;
To implement it, simply use the 'skip' keyword. For example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function addFn(num1, num2){
  return num1 + num2;
}
test.skip('skip test example - skipping the addition test', () =&amp;gt; {
  expect(addFn(2, 3)).toBe(5);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The opposite of this is implementing only a subset of tests, which is achieved by using the 'only' keyword. For example,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function addFn(num1, num2){
  return num1 + num2;
}
test.only('skip test example - skipping the addition test', () =&amp;gt; {
  expect(addFn(2, 3)).toBe(5);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Reference&lt;/strong&gt;:&lt;br&gt;
&lt;a href="https://www.geeksforgeeks.org/testing-with-jest/"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>testing</category>
    </item>
    <item>
      <title>Interfaces in TypeScript</title>
      <dc:creator>Famini-ProDev</dc:creator>
      <pubDate>Sat, 23 Apr 2022 11:38:44 +0000</pubDate>
      <link>https://dev.to/faminiprodev/interfaces-in-typescript-4ne6</link>
      <guid>https://dev.to/faminiprodev/interfaces-in-typescript-4ne6</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
TypeScript is an extension of the JavaScript language that uses JavaScript’s runtime with a compile-time type checker.&lt;br&gt;
TypeScript offers multiple ways to represent objects in your code, one of which is using interfaces. Interfaces in TypeScript have two usage scenarios: you can create a contract that classes must follow, such as the members that those classes must implement, and you can also represent types in your application, just like the normal type declaration. (For more about types, check out How to Use Basic Types in TypeScript and How to Create Custom Types in TypeScript.)&lt;br&gt;
You may notice that interfaces and types share a similar set of features; in fact, one can almost always replace the other. The main difference is that interfaces may have more than one declaration for the same interface, which TypeScript will merge, while types can only be declared once. You can also use types to create aliases of primitive types (such as string and boolean), which interfaces cannot do.&lt;br&gt;
Interfaces in TypeScript are a powerful way to represent type structures. They allow you to make the usage of those structures type-safe and document them simultaneously, directly improving the developer experience.&lt;br&gt;
In this tutorial, you will create interfaces in TypeScript, learn how to use them, and understand the differences between normal types and interfaces. You will try out different code samples, which you can follow in your own TypeScript environment or the TypeScript Playground, an online environment that allows you to write TypeScript directly in the browser.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating and Using Interfaces in TypeScript&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this section, you will create interfaces using different features available in TypeScript. You will also learn how to use the interfaces you created.&lt;br&gt;
Interfaces in TypeScript are created by using the interface keyword followed by the name of the interface, and then a {} block with the body of the interface. For example, here is a Logger interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  log: (message: string) =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similar to creating a normal type using the &lt;code&gt;type&lt;/code&gt;declaration, you specify the fields of the type, and their type, in the &lt;code&gt;{}&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  log: (message: string) =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Logger&lt;/code&gt;interface represents an object that has a single property called &lt;code&gt;log&lt;/code&gt;. This property is a function that accepts a single parameter of type &lt;code&gt;string&lt;/code&gt;and returns &lt;code&gt;void&lt;/code&gt;.&lt;br&gt;
You can use the &lt;code&gt;Logger&lt;/code&gt;interface as any other type. Here is an example creating an object literal that matches the &lt;code&gt;Logger&lt;/code&gt;interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  log: (message: string) =&amp;gt; void;
}
const logger: Logger = {
  log: (message) =&amp;gt; console.log(message),
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Values using the &lt;code&gt;Logger&lt;/code&gt;interface as their type must have the same members as those specified in the &lt;code&gt;Logger&lt;/code&gt;interface declaration. If some members are optional, they may be omitted.&lt;br&gt;
Since values must follow what is declared in the interface, adding extraneous fields will cause a compilation error. For example, in the object literal, try adding a new property that is missing from the interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  log: (message: string) =&amp;gt; void;
}
const logger: Logger = {
  log: (message) =&amp;gt; console.log(message),
  otherProp: true,
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the TypeScript Compiler would emit error 2322, as this property does not exist in the Logger interface declaration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Output
Type '{ log: (message: string) =&amp;gt; void; otherProp: boolean; }' is not assignable to type 'Logger'.
  Object literal may only specify known properties, and 'otherProp' does not exist in type 'Logger'. (2322)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similar to using normal type declarations, properties can be turned into an optional property by appending ? to their name.&lt;/p&gt;

&lt;p&gt;Extending Other Types&lt;br&gt;
When creating interfaces, you can extend from different object types, allowing your interfaces to include all the type information from the extended types. This enables you to write small interfaces with a common set of fields and use them as building blocks to create new interfaces.&lt;br&gt;
Imagine you have a Clearable interface, such as this one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Clearable {
  clear: () =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You could then create a new interface that extends from it, inheriting all its fields. In the following example, the interface Logger is extending from the Clearable interface. Notice the highlighted lines:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Clearable {
  clear: () =&amp;gt; void;
}
interface Logger extends Clearable {
  log: (message: string) =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Logger&lt;/code&gt;interface now also has a &lt;code&gt;clear&lt;/code&gt;member, which is a function that accepts no parameters and returns &lt;code&gt;void&lt;/code&gt;. This new member is inherited from the Clearable interface. It is the same as if we did this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  log: (message: string) =&amp;gt; void;
  clear: () =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When writing lots of interfaces with a common set of fields, you can extract them to a different interface and change your interfaces to extend from the new interface you created.&lt;br&gt;
Returning to the Clearable example used previously, imagine that your application needs a different interface, such as the following StringList interface, to represent a data structure that holds multiple strings:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface StringList {
  push: (value: string) =&amp;gt; void;
  get: () =&amp;gt; string[];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By making this new &lt;code&gt;StringList&lt;/code&gt;interface extend the existing Clearable interface, you are specifying that this interface also has the members set in the Clearable interface, adding the clear property to the type definition of the &lt;code&gt;StringList&lt;/code&gt; interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface StringList extends Clearable {
  push: (value: string) =&amp;gt; void;
  get: () =&amp;gt; string[];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Interfaces can extend from any object type, such as interfaces, normal types, and even classes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interfaces with Callable Signature&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If the interface is also callable (that is, it is also a function), you can convey that information in the interface declaration by creating a callable signature.&lt;br&gt;
A callable signature is created by adding a function declaration inside the interface that is not bound to any member and by using : instead of =&amp;gt; when setting the return type of the function.&lt;br&gt;
As an example, add a callable signature to your Logger interface, as in the highlighted code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  (message: string): void;
  log: (message: string) =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similar to creating a normal type using the type declaration, you specify the fields of the type, and their type, in the &lt;code&gt;{}&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  log: (message: string) =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Logger interface represents an object that has a single property called log. This property is a function that accepts a single parameter of type string and returns void.&lt;br&gt;
You can use the &lt;code&gt;Logger&lt;/code&gt;interface as any other type. Here is an example creating an object literal that matches the &lt;code&gt;Logger&lt;/code&gt;interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  log: (message: string) =&amp;gt; void;
}
const logger: Logger = {
  log: (message) =&amp;gt; console.log(message),
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Values using the &lt;code&gt;Logger&lt;/code&gt;interface as their type must have the same members as those specified in the &lt;code&gt;Logger&lt;/code&gt;interface declaration. If some members are optional, they may be omitted.&lt;br&gt;
Since values must follow what is declared in the interface, adding extraneous fields will cause a compilation error. For example, in the object literal, try adding a new property that is missing from the interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  log: (message: string) =&amp;gt; void;
}
const logger: Logger = {
  log: (message) =&amp;gt; console.log(message),
  otherProp: true,
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the TypeScript Compiler would emit error 2322, as this property does not exist in the Logger interface declaration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Output
Type '{ log: (message: string) =&amp;gt; void; otherProp: boolean; }' is not assignable to type 'Logger'.
  Object literal may only specify known properties, and 'otherProp' does not exist in type 'Logger'. (2322)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similar to using normal &lt;code&gt;type&lt;/code&gt;declarations, properties can be turned into an optional property by appending &lt;code&gt;?&lt;/code&gt;to their name.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Extending Other Types&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When creating interfaces, you can extend from different object types, allowing your interfaces to include all the type information from the extended types. This enables you to write small interfaces with a common set of fields and use them as building blocks to create new interfaces.&lt;br&gt;
Imagine you have a Clearable interface, such as this one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Clearable {
  clear: () =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You could then create a new interface that extends from it, inheriting all its fields. In the following example, the interface Logger is extending from the Clearable interface. Notice the highlighted lines:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Clearable {
  clear: () =&amp;gt; void;
}
interface Logger extends Clearable {
  log: (message: string) =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Logger&lt;/code&gt;interface now also has a &lt;code&gt;clear&lt;/code&gt;member, which is a function that accepts no parameters and returns void. This new member is inherited from the &lt;code&gt;Clearable&lt;/code&gt;interface. It is the same as if we did this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  log: (message: string) =&amp;gt; void;
  clear: () =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When writing lots of interfaces with a common set of fields, you can extract them to a different interface and change your interfaces to extend from the new interface you created.&lt;br&gt;
Returning to the Clearable example used previously, imagine that your application needs a different interface, such as the following &lt;code&gt;StringList&lt;/code&gt;interface, to represent a data structure that holds multiple strings:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface StringList {
  push: (value: string) =&amp;gt; void;
  get: () =&amp;gt; string[];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By making this new &lt;code&gt;StringList&lt;/code&gt;interface extend the existing Clearable interface, you are specifying that this interface also has the members set in the Clearable interface, adding the clear property to the type definition of the &lt;code&gt;StringList&lt;/code&gt;interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface StringList extends Clearable {
  push: (value: string) =&amp;gt; void;
  get: () =&amp;gt; string[];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Interfaces with Callable Signature&lt;br&gt;
If the interface is also callable (that is, it is also a function), you can convey that information in the interface declaration by creating a callable signature.&lt;br&gt;
A callable signature is created by adding a function declaration inside the interface that is not bound to any member and by using : instead of =&amp;gt; when setting the return type of the function.&lt;br&gt;
As an example, add a callable signature to your Logger interface, as in the highlighted code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  (message: string): void;
  log: (message: string) =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that the callable signature resembles the type declaration of an anonymous function, but in the return type you are using : instead of =&amp;gt;. This means that any value bound to the Logger interface type can be called directly as a function.&lt;br&gt;
To create a value that matches your Logger interface, you need to consider the requirements of the interface:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It must be callable.&lt;/li&gt;
&lt;li&gt;It must have a property called log that is a function accepting a single string parameter.
Let’s create a variable called &lt;code&gt;logger&lt;/code&gt;that is assignable to the type of your &lt;code&gt;Logger&lt;/code&gt;interface:
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  (message: string): void;
  log: (message: string) =&amp;gt; void;
}
const logger: Logger = (message: string) =&amp;gt; {
  console.log(message);
}
logger.log = (message: string) =&amp;gt; {
  console.log(message);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;To match the Logger interface, the value must be callable, which is why you assign the logger variable to a function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  (message: string): void;
  log: (message: string) =&amp;gt; void;
}
const logger: Logger = (message: string) =&amp;gt; {
  console.log(message);
}
logger.log = (message: string) =&amp;gt; {
  console.log(message);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You are then adding the log property to the logger function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  (message: string): void;
  log: (message: string) =&amp;gt; void;
}
const logger: Logger = (message: string) =&amp;gt; {
  console.log(message);
}
logger.log = (message: string) =&amp;gt; {
  console.log(message);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is required by the &lt;code&gt;Logger&lt;/code&gt;interface. Values bound to the &lt;code&gt;Logger&lt;/code&gt;interface must also have a &lt;code&gt;log&lt;/code&gt;property that is a function accepting a single string parameter and that returns void.&lt;br&gt;
If you did not include the log property, the TypeScript Compiler would give you error &lt;code&gt;2741&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Output
Property 'log' is missing in type '(message: string) =&amp;gt; void' but required in type 'Logger'. (2741)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The TypeScript Compiler would emit a similar error if the log property in the logger variable had an incompatible type signature, like setting it to true:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  (message: string): void;
  log: (message: string) =&amp;gt; void;
}
const logger: Logger = (message: string) =&amp;gt; {
  console.log(message);
}
logger.log = true;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the TypeScript Compiler would show error 2322:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Output
Type 'boolean' is not assignable to type '(message: string) =&amp;gt; void'. (2322)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A nice feature of setting variables to have a specific type, in this case setting the logger variable to have the type of the Logger interface, is that TypeScript can now infer the type of the parameters of both the logger function and the function in the log property.&lt;/p&gt;

&lt;p&gt;You can check that by removing the type information from the argument of both functions. Notice that in the highlighted code below, the message parameters do not have a type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Logger {
  (message: string): void;
  log: (message: string) =&amp;gt; void;
}
const logger: Logger = (message) =&amp;gt; {
  console.log(message);
}
logger.log = (message) =&amp;gt; {
  console.log(message);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in both cases, your editor should still be able to show that the type of the parameter is a string, as this is the type expected by the &lt;code&gt;Logger&lt;/code&gt;interface.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interfaces with Index Signatures&lt;/strong&gt;&lt;br&gt;
You can add an index signature to your interface, just like you can with normal types, thus allowing the interface to have an unlimited number of properties.&lt;br&gt;
For example, if you wanted to create a &lt;code&gt;DataRecord&lt;/code&gt;interface that has an unlimited number of string fields, you could use the following highlighted index signature:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface DataRecord {

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can then use the &lt;code&gt;DataRecord&lt;/code&gt;interface to set the type of any object that has multiple parameters of type string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface DataRecord {

}
const data: DataRecord = {
  fieldA: "valueA",
  fieldB: "valueB",
  fieldC: "valueC",
  // ...
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this section, you created interfaces using different features available in TypeScript and learned how to use the interfaces you created. In the next section, you’ll learn more about the differences between type and interface declarations, and gain practice with declaration merging and module augmentation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Differences Between Types and Interfaces&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So far, you have seen that the interface declaration and the type declaration are similar, having almost the same set of features.&lt;br&gt;
For example, you created a Logger interface that extended from a&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Clearable interface:
interface Clearable {
  clear: () =&amp;gt; void;
}
interface Logger extends Clearable {
  log: (message: string) =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The same type representation can be replicated by using two type declarations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Clearable = {
  clear: () =&amp;gt; void;
}
type Logger = Clearable &amp;amp; {
  log: (message: string) =&amp;gt; void;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As shown in the previous sections, the interface declaration can be used to represent a variety of objects, from functions to complex objects with an unlimited number of properties. This is also possible with type declarations, even extending from other types, as you can intersect multiple types together using the intersection operator &amp;amp;.&lt;br&gt;
Since type declarations and interface declarations are so similar, you’ll need to consider the specific features unique to each one and be consistent in your codebase. Pick one to create type representations in your codebase, and only use the other one when you need a specific feature only available to it.&lt;br&gt;
For example, the type declaration has a few features that the interface declaration lacks, such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Union types.&lt;/li&gt;
&lt;li&gt;Mapped types.&lt;/li&gt;
&lt;li&gt;Alias to primitive types.
One of the features available only for the interface declaration is declaration merging, which you will learn about in the next section. It is important to note that declaration merging may be useful if you are writing a library and want to give the library users the power to extend the types provided by the library, as this is not possible with type declarations.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Declaration Merging&lt;/strong&gt;&lt;br&gt;
TypeScript can merge multiple declarations into a single one, enabling you to write multiple declarations for the same data structure and having them bundled together by the TypeScript Compiler during compilation as if they were a single type. In this section, you will see how this works and why it is helpful when using interfaces.&lt;br&gt;
Interfaces in TypeScript can be re-opened; that is, multiple declarations of the same interface can be merged. This is useful when you want to add new fields to an existing interface.&lt;br&gt;
For example, imagine that you have an interface named &lt;code&gt;DatabaseOptions&lt;/code&gt;like the following one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
interface DatabaseOptions {
  host: string;
  port: number;
  user: string;
  password: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This interface is going to be used to pass options when connecting to a database.&lt;br&gt;
Later in the code, you declare an interface with the same name but with a single string field called &lt;code&gt;dsnUrl&lt;/code&gt;, like this one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface DatabaseOptions {
  dsnUrl: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the TypeScript Compiler starts reading your code, it will merge all declarations of the &lt;code&gt;DatabaseOptions&lt;/code&gt;interface into a single one. From the TypeScript Compiler point of view, &lt;code&gt;DatabaseOptions&lt;/code&gt;is now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface DatabaseOptions {
  host: string;
  port: number;
  user: string;
  password: string;
  dsnUrl: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The interface includes all the fields you initially declared, plus the new field &lt;code&gt;dsnUrl&lt;/code&gt;that you declared separately. Both declarations have been merged.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Module Augmentation&lt;/strong&gt;&lt;br&gt;
Declaration merging is helpful when you need to augment existing modules with new properties. One use-case for that is when you are adding more fields to a data structure provided by a library. This is relatively common with the Node.js library called express, which allows you to create HTTP servers.&lt;br&gt;
When working with express, a Request and a Response object are passed to your request handlers (functions responsible for providing a response to a HTTP request). The Request object is commonly used to store data specific to a particular request. For example, you could use it to store the logged user that made the initial HTTP request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myRoute = (req: Request, res: Response) =&amp;gt; {
  res.json({ user: req.user });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the request handler sends back to the client a &lt;code&gt;json&lt;/code&gt;with the user field set to the logged user. The logged user is added to the request object in another place in the code, using an express middleware responsible for user authentication.&lt;br&gt;
The type definitions for the &lt;code&gt;Request&lt;/code&gt;interface itself does not have a &lt;code&gt;user&lt;/code&gt;field, so the above code would give the type error &lt;code&gt;2339&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Property 'user' does not exist on type 'Request'. (2339)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Reference : &lt;a href="https://www.digitalocean.com/community/tutorial_series/how-to-code-in-typescript"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Hoisting</title>
      <dc:creator>Famini-ProDev</dc:creator>
      <pubDate>Sat, 23 Apr 2022 11:05:25 +0000</pubDate>
      <link>https://dev.to/faminiprodev/hoisting-1h3o</link>
      <guid>https://dev.to/faminiprodev/hoisting-1h3o</guid>
      <description>&lt;p&gt;By now, you should be fairly comfortable with the idea of scope, and how variables are attached to different levels of scope depending on where and how they are declared. Both function scope and block scope behave by the same rules in this regard: any variable declared within a scope is attached to that scope.&lt;br&gt;
But there’s a subtle detail of how scope attachment works with declarations that appear in various locations within a scope, and that detail is what we will examine here&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chicken or the Egg?&lt;/strong&gt;&lt;br&gt;
There’s a temptation to think that all of the code you see in a JavaScript program is interpreted line-by-line, top-down in order, as the program executes. While that is substantially true, there’s one part of that assumption that can lead to incorrect thinking about your program.&lt;br&gt;
Consider this code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = 2;

var a;

console.log( a );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What do you expect to be printed in the &lt;code&gt;console.log(..)&lt;/code&gt; statement?&lt;br&gt;
Many developers would expect undefined, since the &lt;code&gt;var&lt;/code&gt;a statement comes after the &lt;code&gt;a = 2&lt;/code&gt;, and it would seem natural to assume that the variable is redefined, and thus assigned the default undefined. However, the output will be &lt;code&gt;2&lt;/code&gt;.&lt;br&gt;
Consider another piece of code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log( a );
var a = 2;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You might be tempted to assume that, since the previous snippet exhibited some less-than-top-down looking behavior, perhaps in this snippet, &lt;code&gt;2&lt;/code&gt;will also be printed. Others may think that since the a variable is used before it is declared, this must result in a &lt;code&gt;ReferenceError&lt;/code&gt;being thrown.&lt;br&gt;
Unfortunately, both guesses are incorrect. undefined is the output.&lt;br&gt;
The Compiler Strikes Again&lt;br&gt;
the best way to think about things is that all declarations, both variables and functions, are processed first, before any part of your code is executed.&lt;br&gt;
When you see &lt;code&gt;var a = 2&lt;/code&gt;;, you probably think of that as one statement. But JavaScript actually thinks of it as two statements: &lt;code&gt;var a&lt;/code&gt;; and &lt;code&gt;a = 2&lt;/code&gt;;. The first statement, the declaration, is processed during the compilation phase. The second statement, the assignment, is left in place for the execution phase.&lt;br&gt;
Our first snippet then should be thought of as being handled like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var a;
a = 2;
console.log( a );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;…where the first part is the compilation and the second part is the execution.&lt;br&gt;
Similarly, our second snippet is actually processed as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var a;
console.log( a );
a = 2;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, one way of thinking, sort of metaphorically, about this process, is that variable and function declarations are “moved” from where they appear in the flow of the code to the top of the code. This gives rise to the name hoisting.&lt;br&gt;
In other words, the egg (declaration) comes before the chicken (assignment).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOTE&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Only the declarations themselves are hoisted, while any assignments or other executable logic are left in place. If hoisting were to re-arrange the executable logic of our code, that could wreak havoc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;foo();
function foo() {
    console.log( a ); // undefined
    var a = 2;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function foo’s declaration (which in this case includes the implied value of it as an actual function) is hoisted, such that the call on the first line is able to execute.&lt;br&gt;
It’s also important to note that hoisting is per-scope. So while our previous snippets were simplified in that they only included global scope, the &lt;code&gt;foo(..)&lt;/code&gt; function we are now examining itself exhibits that &lt;code&gt;var&lt;/code&gt;a is hoisted to the top of &lt;code&gt;foo(..)&lt;/code&gt; (not, obviously, to the top of the program). So the program can perhaps be more accurately interpreted like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function foo() {
    var a;
    console.log( a ); // undefined
    a = 2;
}
foo();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Function declarations are hoisted, as we just saw. But function expressions are not.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;foo(); // not ReferenceError, but TypeError!
var foo = function bar() {
    // ...
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The variable identifier foo is hoisted and attached to the enclosing scope (global) of this program, so &lt;code&gt;foo()&lt;/code&gt; doesn’t fail as a &lt;code&gt;ReferenceError&lt;/code&gt;. But foo has no value yet (as it would if it had been a true function declaration instead of expression). So, foo() is attempting to invoke the undefined value, which is a &lt;code&gt;TypeError&lt;/code&gt;illegal operation.&lt;br&gt;
Also recall that even though it’s a named function expression, the name identifier is not available in the enclosing scope:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;foo(); // TypeError
bar(); // ReferenceError
var foo = function bar() {
    // ...
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This snippet is more accurately interpreted (with hoisting) as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var foo;
foo(); // TypeError
bar(); // ReferenceError
foo = function() {
    var bar = ...self...
    // ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Functions First&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Both function declarations and variable declarations are hoisted. But a subtle detail (that can show up in code with multiple “duplicate” declarations) is that functions are hoisted first, and then variables.&lt;br&gt;
Consider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;foo(); // 1
var foo;
function foo() {
    console.log( 1 );
}
foo = function() {
    console.log( 2 );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;1&lt;/code&gt;is printed instead of &lt;code&gt;2&lt;/code&gt;! This snippet is interpreted by the Engine as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function foo() {
    console.log( 1 );
}
foo(); // 1
foo = function() {
    console.log( 2 );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that &lt;code&gt;var&lt;/code&gt;foo was the duplicate (and thus ignored) declaration, even though it came before the function &lt;code&gt;foo()&lt;/code&gt;… declaration, because function declarations are hoisted before normal variables.&lt;br&gt;
While multiple/duplicate &lt;code&gt;var&lt;/code&gt;declarations are effectively ignored, subsequent function declarations do override previous ones.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;foo(); // 3
function foo() {
    console.log( 1 );
}
var foo = function() {
    console.log( 2 );
};
function foo() {
    console.log( 3 );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While this all may sound like nothing more than interesting academic trivia, it highlights the fact that duplicate definitions in the same scope are a really bad idea and will often lead to confusing results.&lt;br&gt;
Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this code implies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;foo(); // "b"
var a = true;
if (a) {
   function foo() { console.log("a"); }
}
else {
   function foo() { console.log("b"); }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, it’s important to note that this behavior is not reliable and is subject to change in future versions of JavaScript, so it’s probably best to avoid declaring functions in blocks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Review&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We can be tempted to look at &lt;code&gt;var a = 2&lt;/code&gt;; as one statement, but the JavaScript engine does not see it that way. It sees &lt;code&gt;var&lt;/code&gt;a and &lt;code&gt;a = 2&lt;/code&gt; as two separate statements, the first one a compiler-phase task, and the second one an execution-phase task.&lt;br&gt;
What this leads to is that all declarations in a scope, regardless of where they appear, are processed first before the code itself is executed. You can visualize this as declarations (variables and functions) being “moved” to the top of their respective scopes, which we call hoisting.&lt;br&gt;
Declarations themselves are hoisted, but assignments, even assignments of function expressions, are not hoisted.&lt;br&gt;
Be careful about duplicate declarations, especially mixed between normal &lt;code&gt;var&lt;/code&gt;declarations and function declarations—peril awaits if you do!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reference&lt;/strong&gt;&lt;br&gt;
You Don’t Know JS: Kyle Simpson Quotes&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Closure in javaScript</title>
      <dc:creator>Famini-ProDev</dc:creator>
      <pubDate>Sat, 23 Apr 2022 10:48:59 +0000</pubDate>
      <link>https://dev.to/faminiprodev/closure-in-javascript-4o1m</link>
      <guid>https://dev.to/faminiprodev/closure-in-javascript-4o1m</guid>
      <description>&lt;p&gt;A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lexical Scoping&lt;/strong&gt;&lt;br&gt;
Consider the following example code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;init()&lt;/code&gt; creates a local variable called name and a function called &lt;code&gt;displayName()&lt;/code&gt;. The &lt;code&gt;displayName()&lt;/code&gt; function is an inner function that is defined inside &lt;code&gt;init()&lt;/code&gt; and is available only within the body of the &lt;code&gt;init()&lt;/code&gt; function. Note that the &lt;code&gt;displayName()&lt;/code&gt; function has no local variables of its own. However, since inner functions have access to the variables of outer functions, &lt;code&gt;displayName()&lt;/code&gt; can access the variable name declared in the parent function, &lt;code&gt;init()&lt;/code&gt;.&lt;br&gt;
Run the code using this JSFiddle link and notice that the &lt;code&gt;alert()&lt;/code&gt; statement within the &lt;code&gt;displayName()&lt;/code&gt; function successfully displays the value of the name variable, which is declared in its parent function. This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Closure&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Consider the following code example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function makeFunc() {
  var name = 'Mozilla';
  function displayName() {
    alert(name);
  }
  return displayName;
}
var myFunc = makeFunc();
myFunc();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Running this code has exactly the same effect as the previous example of the &lt;code&gt;init()&lt;/code&gt; function above. What's different (and interesting) is that the &lt;code&gt;displayName()&lt;/code&gt; inner function is returned from the outer function before being executed.&lt;br&gt;
At first glance, it might seem unintuitive that this code still works. In some programming languages, the local variables within a function exist for just the duration of that function’s execution. Once &lt;code&gt;makeFunc()&lt;/code&gt; finishes executing, you might expect that the name variable would no longer be accessible. However, because the code still works as expected, this is obviously not the case in JavaScript.&lt;br&gt;
The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created. In this case, &lt;code&gt;myFunc&lt;/code&gt;is a reference to the instance of the function &lt;code&gt;displayName&lt;/code&gt;that is created when &lt;code&gt;makeFunc&lt;/code&gt;is run. The instance of &lt;code&gt;displayName&lt;/code&gt;maintains a reference to its lexical environment, within which the variable name exists. For this reason, when &lt;code&gt;myFunc&lt;/code&gt;is invoked, the variable name remains available for use, and &lt;code&gt;"Mozilla"&lt;/code&gt; is passed to alert.&lt;/p&gt;

&lt;p&gt;Here’s a slightly more interesting example — a &lt;code&gt;makeAdder&lt;/code&gt;function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2));  // 7
console.log(add10(2)); // 12
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we have defined a function &lt;code&gt;makeAdder(x)&lt;/code&gt;, that takes a single argument &lt;code&gt;x&lt;/code&gt;, and returns a new function. The function it returns takes a single argument &lt;code&gt;y&lt;/code&gt;, and returns the sum of &lt;code&gt;x&lt;/code&gt;and &lt;code&gt;y&lt;/code&gt;.&lt;br&gt;
In essence, &lt;code&gt;makeAdder&lt;/code&gt;is a function factory. It creates functions that can add a specific value to their argument. In the above example, the function factory creates two new functions—one that adds five to its argument, and one that adds 10.&lt;br&gt;
add5 and add10 are both closures. They share the same function body definition, but store different lexical environments. In add5's lexical environment, &lt;code&gt;x&lt;/code&gt;is 5, while in the lexical environment for add10, &lt;code&gt;x&lt;/code&gt;is 10.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Partical Closures&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object’s properties) with one or more methods.&lt;br&gt;
Consequently, you can use a closure anywhere that you might normally use an object with only a single method.&lt;br&gt;
Situations where you might want to do this are particularly common on the web. Much of the code written in front-end JavaScript is event-based. You define some behavior, and then attach it to an event that is triggered by the user (such as a click or a keypress). The code is attached as a callback (a single function that is executed in response to the event).&lt;br&gt;
For instance, suppose we want to add buttons to a page to adjust the text size. One way of doing this is to specify the font-size of the body element (in pixels), and then set the size of the other elements on the page (such as headers) using the relative &lt;code&gt;em&lt;/code&gt;unit:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 12px;
}
h1 {
  font-size: 1.5em;
}
h2 {
  font-size: 1.2em;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Such interactive text size buttons can change the &lt;code&gt;font-size&lt;/code&gt; property of the &lt;code&gt;body&lt;/code&gt;element, and the adjustments are picked up by other elements on the page thanks to the relative units.&lt;br&gt;
Here’s the JavaScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}
var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;size12&lt;/code&gt;, &lt;code&gt;size14&lt;/code&gt;, and &lt;code&gt;size16&lt;/code&gt;are now functions that resize the body text to 12, 14, and 16 pixels, respectively. You can attach them to buttons (in this case hyperlinks) as demonstrated in the following code example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
&amp;lt;a href="#" id="size-12"&amp;gt;12&amp;lt;/a&amp;gt;
&amp;lt;a href="#" id="size-14"&amp;gt;14&amp;lt;/a&amp;gt;
&amp;lt;a href="#" id="size-16"&amp;gt;16&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Emulating private methods with closures&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Languages such as Java allow you to declare methods as private, meaning that they can be called only by other methods in the same class.&lt;br&gt;
JavaScript previously didn’t have a native way of declaring private methods, but it was possible to emulate private methods using closures. Private methods aren’t just useful for restricting access to code. They also provide a powerful way of managing your global namespace.&lt;br&gt;
The following code illustrates how to use closures to define public functions that can access private functions and variables. Note that these closures follow the Module Design Pattern.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };
})();
console.log(counter.value());  // 0.
counter.increment();
counter.increment();
console.log(counter.value());  // 2.
counter.decrement();
console.log(counter.value());  // 1.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In previous examples, each closure had its own lexical environment. Here though, there is a single lexical environment that is shared by the three functions: &lt;code&gt;counter.increment&lt;/code&gt;, &lt;code&gt;counter.decrement&lt;/code&gt;, and &lt;code&gt;counter.value&lt;/code&gt;.&lt;br&gt;
The shared lexical environment is created in the body of an anonymous function, which is executed as soon as it has been defined (also known as an IIFE). The lexical environment contains two private items: a variable called &lt;code&gt;privateCounter&lt;/code&gt;, and a function called &lt;code&gt;changeBy&lt;/code&gt;. You can't access either of these private members from outside the anonymous function. Instead, you can access them using the three public functions that are returned from the anonymous wrapper.&lt;br&gt;
Those three public functions are closures that share the same lexical environment. Thanks to JavaScript’s lexical scoping, they each have access to the &lt;code&gt;privateCounter&lt;/code&gt;variable and the &lt;code&gt;changeBy&lt;/code&gt;function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var makeCounter = function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  }
};
var counter1 = makeCounter();
var counter2 = makeCounter();
alert(counter1.value());  // 0.
counter1.increment();
counter1.increment();
alert(counter1.value()); // 2.
counter1.decrement();
alert(counter1.value()); // 1.
alert(counter2.value()); // 0.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice how the two counters maintain their independence from one another. Each closure references a different version of the &lt;code&gt;privateCounter&lt;/code&gt;variable through its own closure. Each time one of the counters is called, its lexical environment changes by changing the value of this variable. Changes to the variable value in one closure don't affect the value in the other closure.&lt;/p&gt;

&lt;p&gt;Note: Using closures in this way provides benefits that are normally associated with object-oriented programming. In particular, data hiding and encapsulation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Closure Scope Chain&lt;/strong&gt;&lt;br&gt;
Every closure has three scopes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Local Scope (Own scope)&lt;/li&gt;
&lt;li&gt;Outer Functions Scope&lt;/li&gt;
&lt;li&gt;Global Scope&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A common mistake is not realizing that in the case where the outer function is itself a nested function, access to the outer function’s scope includes the enclosing scope of the outer function — effectively creating a chain of function scopes. To demonstrate, consider the following example code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// global scope
var e = 10;
function sum(a){
  return function(b){
    return function(c){
      // outer functions scope
      return function(d){
        // local scope
        return a + b + c + d + e;
      }
    }
  }
}
console.log(sum(1)(2)(3)(4)); // log 20
// You can also write without anonymous functions:
// global scope
var e = 10;
function sum(a){
  return function sum2(b){
    return function sum3(c){
      // outer functions scope
      return function sum4(d){
        // local scope
        return a + b + c + d + e;
      }
    }
  }
}
var sum2 = sum(1);
var sum3 = sum2(2);
var sum4 = sum3(3);
var result = sum4(4);
console.log(result) //log 20
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, there’s a series of nested functions, all of which have access to the outer functions’ scope. In this context, we can say that closures have access to all outer function scopes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating Closures in loops : A Common mistake&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Prior to the introduction of the &lt;code&gt;let&lt;/code&gt;keyword in ECMAScript 2015, a common problem with closures occurred when you created them inside a loop. To demonstrate, consider the following example code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;p id="help"&amp;gt;Helpful notes will appear here&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;E-mail: &amp;lt;input type="text" id="email" name="email"&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Name: &amp;lt;input type="text" id="name" name="name"&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Age: &amp;lt;input type="text" id="age" name="age"&amp;gt;&amp;lt;/p&amp;gt;
function showHelp(help) {
  document.getElementById('help').textContent = help;
}
function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];
  for (var i = 0; i &amp;lt; helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus = function() {
      showHelp(item.help);
    }
  }
}
setupHelp();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Try running the code in JSFiddle.&lt;br&gt;
The helpText array defines three helpful hints, each associated with the ID of an input field in the document. The loop cycles through these definitions, hooking up an onfocus event to each one that shows the associated help method.&lt;br&gt;
If you try this code out, you’ll see that it doesn’t work as expected. No matter what field you focus on, the message about your age will be displayed.&lt;br&gt;
The reason for this is that the functions assigned to onfocus are closures; they consist of the function definition and the captured environment from the setupHelp function's scope. Three closures have been created by the loop, but each one shares the same single lexical environment, which has a variable with changing values (item). This is because the variable item is declared with var and thus has function scope due to hoisting. The value of item.help is determined when the onfocus callbacks are executed. Because the loop has already run its course by that time, the item variable object (shared by all three closures) has been left pointing to the last entry in the helpText list.&lt;br&gt;
One solution in this case is to use more closures: in particular, to use a function factory as described earlier:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function showHelp(help) {
  document.getElementById('help').textContent = help;
}
function makeHelpCallback(help) {
  return function() {
    showHelp(help);
  };
}
function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];
  for (var i = 0; i &amp;lt; helpText.length; i++) {
    var item = helpText[i];
    document.getElementById(item.id).onfocus = makeHelpCallback(item.help);
  }
}
setupHelp();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This works as expected. Rather than the callbacks all sharing a single lexical environment, the &lt;code&gt;makeHelpCallback&lt;/code&gt;function creates a new lexical environment for each callback, in which &lt;code&gt;help&lt;/code&gt;refers to the corresponding string from the &lt;code&gt;helpText&lt;/code&gt;array.&lt;br&gt;
One other way to write the above using anonymous closures is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function showHelp(help) {
  document.getElementById('help').textContent = help;
}
function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];
  for (var i = 0; i &amp;lt; helpText.length; i++) {
    (function() {
       var item = helpText[i];
       document.getElementById(item.id).onfocus = function() {
         showHelp(item.help);
       }
    })(); // Immediate event listener attachment with the current value of item (preserved until iteration).
  }
}
setupHelp();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you don’t want to use more closures, you can use the &lt;code&gt;let&lt;/code&gt;keyword introduced in ES2015 :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function showHelp(help) {
  document.getElementById('help').textContent = help;
}
function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];
  for (let i = 0; i &amp;lt; helpText.length; i++) {
    let item = helpText[i];
    document.getElementById(item.id).onfocus = function() {
      showHelp(item.help);
    }
  }
}
setupHelp();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example uses let instead of var, so every closure binds the block-scoped variable, meaning that no additional closures are required.&lt;br&gt;
Another alternative could be to use &lt;code&gt;forEach()&lt;/code&gt; to iterate over the &lt;code&gt;helpText&lt;/code&gt;array and attach a listener to each &lt;code&gt;&amp;lt;input&amp;gt;&lt;/code&gt;, as shown:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function showHelp(help) {
  document.getElementById('help').textContent = help;
}
function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];
  helpText.forEach(function(text) {
    document.getElementById(text.id).onfocus = function() {
      showHelp(text.help);
    }
  });
}
setupHelp();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Performance Considerations&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption.&lt;br&gt;
For instance, when creating a new object/class, methods should normally be associated to the object’s prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation).&lt;br&gt;
Consider the following case:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function MyObject(name, message) {
  this.name = name.toString();
  this.message = message.toString();
  this.getName = function() {
    return this.name;
  };
  this.getMessage = function() {
    return this.message;
  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because the previous code does not take advantage of the benefits of using closures in this particular instance, we could instead rewrite it to avoid using closures as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function MyObject(name, message) {
  this.name = name.toString();
  this.message = message.toString();
}
MyObject.prototype = {
  getName: function() {
    return this.name;
  },
  getMessage: function() {
    return this.message;
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, redefining the prototype is not recommended. The following example instead appends to the existing prototype:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function MyObject(name, message) {
  this.name = name.toString();
  this.message = message.toString();
}
MyObject.prototype.getName = function() {
  return this.name;
};
MyObject.prototype.getMessage = function() {
  return this.message;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Refrences&lt;/strong&gt; : &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Async Nature Of setState() (React js)</title>
      <dc:creator>Famini-ProDev</dc:creator>
      <pubDate>Fri, 22 Apr 2022 15:04:31 +0000</pubDate>
      <link>https://dev.to/faminiprodev/async-nature-of-setstate-react-js-mle</link>
      <guid>https://dev.to/faminiprodev/async-nature-of-setstate-react-js-mle</guid>
      <description>&lt;p&gt;Gist:&lt;br&gt;
React batches updates and flushes it out once per frame (perf optimization) However, in some cases React has no control over batching, hence updates are made synchronously eg. eventListeners, Ajax, setTimeout and similar Web APIs&lt;br&gt;
Main Idea&lt;br&gt;
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.&lt;br&gt;
Run the below code and you will make the following observations:&lt;br&gt;
You can see that in every situation (addEventListener, setTimeout or AJAX call) the state before and the state after are different. And that render was called immediately after triggering the setState method. But why is that? Well, it turns out React does not understand and thus cannot control code that doesn’t live inside the library. Timeouts or AJAX calls for example, are developer authored code that executes outside of the context of React.&lt;br&gt;
So why does React synchronously update the state in these cases? Well, because it’s trying to be as defensive as possible. Not being in control means it’s not able to do any performance optimisations so it’s better to update the state on spot and make sure the code that follows has access to the latest information available.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class TestComponent extends React.Component {
  constructor(...args) {
    super(...args);
    this.state = {
      dollars: 10
    };
    this._saveButtonRef = (btn =&amp;gt; { this._btnRef = btn });
    [
      '_onTimeoutHandler',
      '_onMouseLeaveHandler',
      '_onClickHandler',
      '_onAjaxCallback',
    ].forEach(propToBind =&amp;gt; {
      this[propToBind] = this[propToBind].bind(this);
    });
  }

  componentDidMount() {
    // Add custom event via `addEventListener`
    //
    // The list of supported React events does include `mouseleave`
    // via `onMouseLeave` prop
    //
    // However, we are not adding the event the `React way` - this will have
    // effects on how state mutates
    //
    // Check the list here - https://reactjs.org/docs/events.html
    this._btnRef.addEventListener('mouseleave', this._onMouseLeaveHandler);

    // Add JS timeout
    //
    // Again,outside React `world` - this will also have effects on how state
    // mutates
    setTimeout(this._onTimeoutHandler, 10000);

    // Make AJAX request
    fetch('https://api.github.com/users')
      .then(this._onAjaxCallback);
  }

  render() {
    console.log('State in render: ' + JSON.stringify(this.state));

    return (
       &amp;lt;button
         ref={this._saveButtonRef}
         onClick={this._onClickHandler}&amp;gt;
         'Click me'
      &amp;lt;/button&amp;gt;
    );
  }

  _onClickHandler() {
    console.log('State before (_onClickHandler): ' + JSON.stringify(this.state));
    this.setState({
      dollars: this.state.dollars + 10
    });
    console.log('State after (_onClickHandler): ' + JSON.stringify(this.state));
  }

  _onMouseLeaveHandler() {
    console.log('State before (mouseleave): ' + JSON.stringify(this.state));
    this.setState({
      dollars: this.state.dollars + 20
    });
    console.log('State after (mouseleave): ' + JSON.stringify(this.state));
  }

  _onTimeoutHandler() {
    console.log('State before (timeout): ' + JSON.stringify(this.state));
    this.setState({
      dollars: this.state.dollars + 30
    });
    console.log('State after (timeout): ' + JSON.stringify(this.state));
  }

  _onAjaxCallback(response) {
    if (response.status !== 200) {
      console.log('Error in AJAX call: ' + response.statusText);
      return;
    }
    console.log('State before (AJAX call): ' + JSON.stringify(this.state));
    this.setState({
      dollars: this.state.dollars + 40
    });
    console.log('State after (AJAX call): ' + JSON.stringify(this.state));
  }
};

// Render to DOM
ReactDOM.render(
  &amp;lt;TestComponent /&amp;gt;,
  document.getElementById('app')
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Possible solution?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We’re used to calling setState with one parameter only, but actually, the method’s signature support two. The second argument that you can pass in is a callback function that will always be executed after the state has been updated (whether it’s inside React’s known context or outside of it).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;An example might be:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_onClickHandler: function _onClickHandler() {
   console.log('State before (_onClickHandler): ' + JSON.stringify(this.state));
   this.setState({
   dollars: this.state.dollars + 10
   }, () =&amp;gt; {
   console.log('Here state will always be updated to latest version!');
   console.log('State after (_onClickHandler): ' + JSON.stringify(this.state));
   });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;A note on the async nature of setstate&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To be politically correct, setState, as a method, is always synchronous. It's just a function that calls something behind the scenes - enqueueState or enqueueCallback on updater.&lt;br&gt;
In fact, here's setState taken directly from React source code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ReactComponent.prototype.setState = function(partialState, callback) {
  invariant(
    typeof partialState === 'object' ||
    typeof partialState === 'function' ||
    partialState == null,
    'setState(...): takes an object of state variables to update or a ' +
    'function which returns an object of state variables.'
  );
  this.updater.enqueueSetState(this, partialState);
  if (callback) {
    this.updater.enqueueCallback(this, callback, 'setState');
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What's actually sync or async are the effects of calling setState in a React application - the reconciliation algorithm, doing the VDOM comparisons and calling render to update the real DOM.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reference :&lt;/strong&gt;&lt;br&gt;
React-bits :Design Patterns and Techniques&lt;/p&gt;

</description>
      <category>react</category>
    </item>
    <item>
      <title>Component Lifecycle's</title>
      <dc:creator>Famini-ProDev</dc:creator>
      <pubDate>Fri, 22 Apr 2022 14:51:59 +0000</pubDate>
      <link>https://dev.to/faminiprodev/component-lifecycles-2n7</link>
      <guid>https://dev.to/faminiprodev/component-lifecycles-2n7</guid>
      <description>&lt;p&gt;React components live certain life events that are called lifecycle events. These lifecycle's events are tied to lifecycle methods. I discussed several of these methods at the start of this chapter when discusses the creation of components.&lt;br&gt;
The lifecycle methods provide hooks into the phases and the nature of a component. In the code example, taken from section 6.2, I am console logging the occurrence of the lifecycle events &lt;code&gt;componentDidMount&lt;/code&gt;, &lt;code&gt;componentWillUnmount&lt;/code&gt;, and &lt;code&gt;getInitialState&lt;/code&gt;lifecycle methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var Timer = React.createClass({
    getInitialState: function() { 
        console.log('getInitialState lifecycle method ran!');
        return {secondsElapsed: Number(this.props.startTime) || 0};
    },
    tick: function() {
        console.log(ReactDOM.findDOMNode(this));
        if(this.state.secondsElapsed === 65){
            ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);
            return;
        }
        this.setState({secondsElapsed: this.state.secondsElapsed + 1});
    },
    componentDidMount: function() {
        console.log('componentDidMount lifecycle method ran!');
        this.interval = setInterval(this.tick, 1000);
    },
    componentWillUnmount: function() {
        console.log('componentWillUnmount lifecycle method ran!');
        clearInterval(this.interval);
    },
    render: function() {
        return (&amp;lt;div&amp;gt;Seconds Elapsed: {this.state.secondsElapsed}&amp;lt;/div&amp;gt;);
    }
});

ReactDOM.render(&amp;lt; Timer startTime = "60" / &amp;gt;, app);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The methods can be divided into three categories (Mounting, Updating, and Unmounting phases).&lt;br&gt;
Below I show a table for each category and the containing lifecycle methods.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mounting Phase (happens once in a components life):&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The first phase of the React Component life cycle is the Birth/Mounting phase. This is where we start initialization of the Component. At this phase, the Component's props and state are defined and configured. The Component and all its children are mounted on to the Native UI Stack (DOM, UIView, etc.). Finally, we can do post-processing if required. The Birth/Mounting phase only occurs once.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qeD_FUlP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c88fndf8yl11yy1w8mn3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qeD_FUlP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c88fndf8yl11yy1w8mn3.png" alt="Image description" width="800" height="269"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Updating Phase (happens over and over in a components life):&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The next phase of the life cycle is the Growth/Update phase. In this phase, we get new props, change state, handle user interactions and communicate with the component hierarchy. This is where we spend most of our time in the Component's life. Unlike Birth or Death, we repeat this phase over and over.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mUJNTq5d--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvyvvhi81fivz709msdp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mUJNTq5d--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvyvvhi81fivz709msdp.png" alt="Image description" width="800" height="522"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Unmounting Phase (happens once in a components life): *&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The final phase of the life cycle is the Death/Unmount phase. This phase occurs when a component instance is unmounted from the Native UI. This can occur when the user navigates away, the UI page changes, a component is hidden (like a drawer), etc. Death occurs once and readies the Component for Garbage Collection.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--muAtvyJP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2boq9aey9msi5v5cmc67.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--muAtvyJP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2boq9aey9msi5v5cmc67.png" alt="Image description" width="800" height="145"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reference &lt;/strong&gt;:&lt;br&gt;
How to React EnlightenmentTypeScript &lt;/p&gt;

</description>
      <category>react</category>
    </item>
    <item>
      <title>Use axios with React</title>
      <dc:creator>Famini-ProDev</dc:creator>
      <pubDate>Fri, 22 Apr 2022 14:39:03 +0000</pubDate>
      <link>https://dev.to/faminiprodev/use-axios-with-react-4ebg</link>
      <guid>https://dev.to/faminiprodev/use-axios-with-react-4ebg</guid>
      <description>&lt;p&gt;Many projects on the web need to interface with a REST API at some stage in their development. Axios is a lightweight HTTP client based on the &lt;code&gt;$http&lt;/code&gt; service within Angular.js v1.x and is similar to the native JavaScript Fetch API.&lt;br&gt;
Axios is promise-based, which gives you the ability to take advantage of JavaScript’s &lt;code&gt;async&lt;/code&gt;and &lt;code&gt;await&lt;/code&gt;for more readable asynchronous code.&lt;br&gt;
You can also intercept and cancel requests, and there’s built-in client-side protection against cross-site request forgery.&lt;br&gt;
In this article, you will see examples of how to use Axios to access the popular JSON Placeholder API within a React application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1 — Adding Axios to the Project&lt;/strong&gt;&lt;br&gt;
In this section, you will add Axios to a React project&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npx create-react-app react-axios-example
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To add Axios to the project, open your terminal and change directories into your project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ cd react-axios-example
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then run this command to install Axios:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm install axios@0.24.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, you will need to import Axios into the file you want to use it in.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2 — Making a &lt;code&gt;GET&lt;/code&gt;Request&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this example, you create a new component and import Axios into it to send a &lt;code&gt;GET&lt;/code&gt;request.&lt;br&gt;
Inside your React project, you will need to create a new component named &lt;code&gt;PersonList&lt;/code&gt;.&lt;br&gt;
First, create a new &lt;code&gt;components&lt;/code&gt;subdirectory in the &lt;code&gt;src&lt;/code&gt;directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ mkdir src/components
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this directory, create &lt;code&gt;PersonList.js&lt;/code&gt; and add the following code to the component:&lt;br&gt;
src/components/PersonList.js:&lt;/p&gt;

&lt;p&gt;import React from 'react';&lt;br&gt;
import axios from 'axios';&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default class PersonList extends React.Component {
  state = {
    persons: []
  }

  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/users`)
      .then(res =&amp;gt; {
        const persons = res.data;
        this.setState({ persons });
      })
  }

  render() {
    return (
      &amp;lt;ul&amp;gt;
        {
          this.state.persons
            .map(person =&amp;gt;
              &amp;lt;li key={person.id}&amp;gt;{person.name}&amp;lt;/li&amp;gt;
            )
        }
      &amp;lt;/ul&amp;gt;
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, you import React and Axios so that both can be used in the component. Then you hook into the &lt;code&gt;componentDidMount&lt;/code&gt;lifecycle hook and perform a &lt;code&gt;GET&lt;/code&gt;request.&lt;/p&gt;

&lt;p&gt;You use &lt;code&gt;axios.get(url)&lt;/code&gt; with a URL from an API endpoint to get a promise which returns a response object. Inside the response object, there is data that is then assigned the value of person.&lt;/p&gt;

&lt;p&gt;You can also get other information about the request, such as the status code under &lt;code&gt;res.status&lt;/code&gt; or more information inside of &lt;code&gt;res.request&lt;/code&gt;.&lt;br&gt;
Add this component to your &lt;code&gt;app.js&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;import PersonList from './components/PersonList.js';&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  return (
    &amp;lt;div ClassName="App"&amp;gt;
      &amp;lt;PersonList/&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then run your application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;View the application in the browser. You will be presented with a list of 10 names.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3 — Making a &lt;code&gt;POST&lt;/code&gt;Request&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this step, you will use Axios with another HTTP request method called &lt;code&gt;POST&lt;/code&gt;.&lt;br&gt;
Inside your React project, you will need to create a new component named &lt;code&gt;PersonAdd&lt;/code&gt;.&lt;br&gt;
Create &lt;code&gt;PersonAdd.js&lt;/code&gt; and add the following code to create a form that allows for user input and subsequently &lt;code&gt;POSTs&lt;/code&gt;the content to an API:&lt;/p&gt;

&lt;p&gt;src/components/PersonAdd.js:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import axios from 'axios';

export default class PersonAdd extends React.Component {
  state = {
    name: ''
  }

  handleChange = event =&amp;gt; {
    this.setState({ name: event.target.value });
  }

  handleSubmit = event =&amp;gt; {
    event.preventDefault();

    const user = {
      name: this.state.name
    };

    axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
      .then(res =&amp;gt; {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
          &amp;lt;label&amp;gt;
            Person Name:
            &amp;lt;input type="text" name="name" onChange={this.handleChange} /&amp;gt;
          &amp;lt;/label&amp;gt;
          &amp;lt;button type="submit"&amp;gt;Add&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
      &amp;lt;/div&amp;gt;
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside the &lt;code&gt;handleSubmit&lt;/code&gt;function, you prevent the default action of the form. Then update the &lt;code&gt;state&lt;/code&gt;to the &lt;code&gt;user&lt;/code&gt;input.&lt;br&gt;
Using &lt;code&gt;POST&lt;/code&gt;gives you the same response object with information that you can use inside of a &lt;code&gt;then&lt;/code&gt;call.&lt;br&gt;
To complete the &lt;code&gt;POST&lt;/code&gt;request, you first capture the &lt;code&gt;user&lt;/code&gt;input. Then you add the input along with the &lt;code&gt;POST&lt;/code&gt;request, which will give you a response. You can then &lt;code&gt;console.log&lt;/code&gt; the response, which should show the user input in the form.&lt;br&gt;
Add this component to your &lt;code&gt;app.js&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;src/app.js:&lt;/p&gt;

&lt;p&gt;import PersonList from './components/PersonList';&lt;br&gt;
import PersonAdd from './components/PersonAdd';&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
  return (
    &amp;lt;div ClassName="App"&amp;gt;
      &amp;lt;PersonAdd/&amp;gt;
      &amp;lt;PersonList/&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then run your application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;View the application in the browser. You will be presented with a form for submitting new users. Check the console after submitting a new user.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4 — Making a &lt;code&gt;DELETE&lt;/code&gt;Request&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this example, you will see how to delete items from an API using &lt;code&gt;axios.delete&lt;/code&gt; and passing a URL as a parameter.&lt;br&gt;
Inside your React project, you will need to create a new component named PersonRemove.&lt;br&gt;
Create &lt;code&gt;PersonRemove.js&lt;/code&gt; and add the following code to delete a user:&lt;br&gt;
src/PersonRemove.js :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import axios from 'axios';

export default class PersonRemove extends React.Component {
  state = {
    id: ''
  }

  handleChange = event =&amp;gt; {
    this.setState({ id: event.target.value });
  }

  handleSubmit = event =&amp;gt; {
    event.preventDefault();

    axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)
      .then(res =&amp;gt; {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
          &amp;lt;label&amp;gt;
            Person ID:
            &amp;lt;input type="number" name="id" onChange={this.handleChange} /&amp;gt;
          &amp;lt;/label&amp;gt;
          &amp;lt;button type="submit"&amp;gt;Delete&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
      &amp;lt;/div&amp;gt;
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Again, the res object provides you with information about the request. You can then &lt;code&gt;console.log&lt;/code&gt; that information again after the form is submitted.&lt;br&gt;
Add this component to your &lt;code&gt;app.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import PersonList from './components/PersonList';
import PersonAdd from './components/PersonAdd';
import PersonRemove from './components/PersonRemove';

function App() {
  return (
    &amp;lt;div ClassName="App"&amp;gt;
      &amp;lt;PersonAdd/&amp;gt;
      &amp;lt;PersonList/&amp;gt;
      &amp;lt;PersonRemove/&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then run your application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;View the application in the browser. You will be presented with a form for removing users.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5 — Using a Base Instance in Axios&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this example, you will see how you can set up a base instance in which you can define a URL and any other configuration elements.&lt;br&gt;
Create a separate file named &lt;code&gt;api.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ nano src/api.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Export a new &lt;code&gt;axios&lt;/code&gt;instance with these defaults:&lt;br&gt;
src/api.js :&lt;/p&gt;

&lt;p&gt;import axios from 'axios';&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default axios.create({
  baseURL: `http://jsonplaceholder.typicode.com/`
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the default instance is set up, it can then be used inside of the &lt;code&gt;PersonRemove&lt;/code&gt;component. You import the new instance like this:&lt;br&gt;
src/components/PersonRemove.js :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';

import API from '../api';

export default class PersonRemove extends React.Component {
  // ...

  handleSubmit = event =&amp;gt; {
    event.preventDefault();

    API.delete(`users/${this.state.id}`)
      .then(res =&amp;gt; {
        console.log(res);
        console.log(res.data);
      })
  }

  // ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because &lt;code&gt;http://jsonplaceholder.typicode.com/&lt;/code&gt; is now the base URL, you no longer need to type out the whole URL each time you want to hit a different endpoint on the API.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 6 — Using &lt;code&gt;async&lt;/code&gt;and &lt;code&gt;await&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this example, you will see how you can use &lt;code&gt;async&lt;/code&gt;and &lt;code&gt;await&lt;/code&gt;to work with promises.&lt;br&gt;
The &lt;code&gt;await&lt;/code&gt;keyword resolves the &lt;code&gt;promise&lt;/code&gt;and returns the &lt;code&gt;value&lt;/code&gt;. The &lt;code&gt;value&lt;/code&gt;can then be assigned to a variable.&lt;/p&gt;

&lt;p&gt;src/components/PersonRemove.js :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';

import API from '../api';

export default class PersonRemove extends React.Component {
  // ...

  handleSubmit = event =&amp;gt; {
    event.preventDefault();

    const response = await API.delete(`users/${this.state.id}`);

    console.log(response);
    console.log(response.data);
  }

  // ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;*&lt;em&gt;Refrences : *&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.digitalocean.com/community/tutorial_series/how-to-code-in-react-js"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.digitalocean.com/community/tags/react"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
    </item>
    <item>
      <title>7 JavaScript Design Patterns Every developer should knows.</title>
      <dc:creator>Famini-ProDev</dc:creator>
      <pubDate>Fri, 22 Apr 2022 13:59:10 +0000</pubDate>
      <link>https://dev.to/faminiprodev/7-javascript-design-patterns-every-developer-should-knows-1ke5</link>
      <guid>https://dev.to/faminiprodev/7-javascript-design-patterns-every-developer-should-knows-1ke5</guid>
      <description>&lt;p&gt;Design patterns help combine experiences of many developers to structure the codes in an optimized manner that meet the problems we are seeking solutions to, and gives common vocabulary used to describe solutions to our problems than describing the syntax and semantics of our code.&lt;br&gt;
JavaScript design patterns assist developers to write organized, beautiful and well-structured codes. Although design patterns, when used can easily be re-used, they can never supplement developers, rather they only support them by preventing minor issues that could lead to major problems on the web application development by providing generalized solutions that are not tied to a specific problem.&lt;br&gt;
They decrease the overall codebase by doing away with unnecessary repetitions, thus makes our code more robust than the ad-hoc solutions.&lt;br&gt;
In this article, I will explore seven best and most popular JavaScript design patterns, which of course most of them will fall under three categories namely; creation design patterns, structural design patterns, and behavioral design patterns. A pattern is something like the following image; just to acquaint you into the context.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Constructor Design Pattern.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is a special method that is used to initialize the newly created objects once a memory is allocated. Since JavaScript is typically object-oriented, it deals with objects most, therefore I intend to delve in to object constructors. There are three ways to create new objects in JavaScript:&lt;br&gt;
The following is one way to create a constructor design pattern.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// This creates a new empty Object
var newObject = {};
// This creates a new empty Object
var newObject = Object.create(Object.prototype);
var newObject = newObject();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To access the properties of a function, you need to initialize the object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const object = new ConstructorObject()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Whereby the new keyword above tells JavaScript that a &lt;code&gt;constructorObject&lt;/code&gt;should act as a constructor. Inheritance is one thing this design pattern does not support. Find out more detail &lt;a href="https://www.patterns.dev/posts/classic-design-patterns/#constructorpatternjavascript"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Prototype Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The prototype pattern is based on prototypical inheritance whereby objects created to act as prototypes for other objects. In reality, prototypes act as a blueprint for each object constructor created.&lt;br&gt;
&lt;em&gt;Example&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name:"Ford",
brake:function(){
console.log("Stop! I am applying brakes");
}
Panic : function (){
console.log ( "wait. how do you stop thuis thing?")
}
}
// use objec create to instansiate a new car
var yourCar= object.create(myCar);
//You can now see that one is a prototype of the other
console.log (yourCar.name);]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Module Design Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the module design pattern, there is an improvement from the prototype pattern. The different types of modifiers (both private and public) are set in the module pattern. You can create similar functions or properties without conflicts. There is the flexibility of renaming functions publicly. The daunting part of this is the inability to override the created functions from the outside environment.&lt;br&gt;
&lt;em&gt;Example&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var myCar= {
function AnimalContainter () {
const container = [];
function addAnimal (name) {
container.push(name);
}
function getAllAnimals() {
return container;
}
function removeAnimal(name) {
const index = container.indexOf(name);
if(index &amp;lt; 1) {
throw new Error('Animal not found in container');
}
container.splice(index, 1)
}
return {
add: addAnimal,
get: getAllAnimals,
remove: removeAnimal
}
}
const container = AnimalContainter();
container.add('Hen');
container.add('Goat');
container.add('Sheep');
console.log(container.get()) //Array(3) ["Hen", "Goat", "Sheep"]
container.remove('Sheep')
console.log(container.get()); //Array(2) ["Hen", "Goat"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Singleton Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is essential in a scenario where only one instance needs to be created, for example, a database connection. It is only possible to create an instance when the connection is closed or you make sure to close the open instance before opening a new one. This pattern is also referred to as strict pattern, one drawback associated with this pattern is its daunting experience in testing because of its hidden dependencies objects which are not easily singled out for testing.&lt;br&gt;
&lt;em&gt;Example&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function DatabaseConnection () {
let databaseInstance = null;
// tracks the number of instances created at a certain time
let count = 0;
function init() {
console.log(`Opening database #${count + 1}`);
//now perform operation
}
function createIntance() {
if(databaseInstance == null) {
databaseInstance = init();
}
return databaseInstance;
}
function closeIntance() {
console.log('closing database');
databaseInstance = null;
}
return {
open: createIntance,
close: closeIntance
}
}
const database = DatabseConnection();
database.open(); //Open database #1
database.open(); //Open database #1
database.open(); //Open database #1
database.close(); //close database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Factory Pattern.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is a creational concerned with the creation of objects without the need for a constructor. It provides a generic interface for creating objects, where we can specify the type of factory objects to be created. Therefore, we only specify the object and the factory instantiates and returns it for us to use. It is wise for us to use factory pattern when the object component set up has a high level of complexity and when we want to create different instances of objects easily depending on the environment we are in. We can also use factory pattern when working with many small objects sharing the same properties and when composing objects that need decoupling.&lt;br&gt;
&lt;em&gt;Example&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Dealer A
DealerA = {};
DealerA.title = function title() {
return "Dealer A";
};
DealerA.pay = function pay(amount) {
console.log(
`set up configuration using username: ${this.username} and password: ${
this.password
}`
);
return `Payment for service ${amount} is successful using ${this.title()}`;
};
//Dealer B
DealerB = {};
DealerB.title = function title() {
return "Dealer B";
};
DealerB.pay = function pay(amount) {
console.log(
`set up configuration using username: ${this.username}
and password: ${this.password}`
);
return `Payment for service ${amount} is successful using ${this.title()}`;
};
//@param {*} DealerOption
//@param {*} config
function DealerFactory(DealerOption, config = {}) {
const dealer = Object.create(dealerOption);
Object.assign(dealer, config);
return dealer;
}
const dealerFactory = DealerFactory(DealerA, {
username: "user",
password: "pass"
});
console.log(dealerFactory.title());
console.log(dealerFactory.pay(12));
const dealerFactory2 = DealerFactory(DealerB, {
username: "user2",
password: "pass2"
});
console.log(dealerFactory2.title());
console.log(dealerFactory2.pay(50));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Observer Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The observer design pattern is handy in a place where objects communicate with other sets of objects simultaneously. In this observer pattern, there is no unnecessary push and pull of events across the states, rather the modules involved only modify the current state of data.&lt;br&gt;
&lt;em&gt;Example&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Observer() {
this.observerContainer = [];
}
Observer.prototype.subscribe = function (element) {
this.observerContainer.push(element);
}
// the following removes an element from the container
Observer.prototype.unsubscribe = function (element) {
const elementIndex = this.observerContainer.indexOf(element);
if (elementIndex &amp;amp;gt; -1) {
this.observerContainer.splice(elementIndex, 1);
}
}
/**
* we notify elements added to the container by calling
* each subscribed components added to our container
*/
Observer.prototype.notifyAll = function (element) {
this.observerContainer.forEach(function (observerElement) {
observerElement(element);
});
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;7. Command Pattern&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To wrap up, I would say the command design pattern ends my 7 best sums of JavaScript design patterns. The command design pattern encapsulates method invocation, operations, or requests into a single object so that we can pass method calls at our discretion. The command design pattern gives us an opportunity to issue commands from anything executing commands and delegates responsibility to different objects instead. These commands are presented in &lt;code&gt;run()&lt;/code&gt; and &lt;code&gt;execute()&lt;/code&gt; format.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(function(){
var carManager = {
//information requested
requestInfo: function( model, id ){
return "The information for " + model + " with ID " + id + " is foo bar";
},
// now purchase the car
buyVehicle: function( model, id ){
return "You have successfully purchased Item " + id + ", a " + model;
},
// now arrange a viewing
arrangeViewing: function( model, id ){
return "You have successfully booked a viewing of " + model + " ( " + id + " ) ";
}
};
})();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Reference&lt;/strong&gt;:&lt;br&gt;
Learning Javascript design Patterns : Addy Osmani&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Understanding Asynchronous Redux Actions with Redux Thunk</title>
      <dc:creator>Famini-ProDev</dc:creator>
      <pubDate>Fri, 22 Apr 2022 13:37:55 +0000</pubDate>
      <link>https://dev.to/faminiprodev/understanding-asynchronous-redux-actions-with-redux-thunk-4lb9</link>
      <guid>https://dev.to/faminiprodev/understanding-asynchronous-redux-actions-with-redux-thunk-4lb9</guid>
      <description>&lt;p&gt;By default, Redux’s actions are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects. Redux also allows for middleware that sits between an action being dispatched and the action reaching the reducers.&lt;br&gt;
There are two very popular middleware libraries that allow for side effects and asynchronous actions: Redux Thunk and Redux Saga. In this post, you will explore Redux Thunk.&lt;br&gt;
Thunk is a programming concept where a function is used to delay the evaluation/calculation of an operation.&lt;br&gt;
Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions inside the function’s body once the asynchronous operations have been completed.&lt;br&gt;
In this article, you will learn how to add Redux Thunk and how it can fit in a hypothetical Post List application.&lt;br&gt;
.The first step:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adding redux-thunk&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, use the terminal to navigate to the project directory and install the redux-thunk package in your project:&lt;/p&gt;

&lt;p&gt;npm install &lt;a href="mailto:redux-thunk@2.1.0"&gt;redux-thunk@2.1.0&lt;/a&gt;``&lt;/p&gt;

&lt;p&gt;Now apply the middleware when creating your app’s store using Redux’s applyMiddleware. Given a React application with redux and react-redux, your &lt;code&gt;configurationStore.js&lt;/code&gt; file might look like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;`&lt;br&gt;
import { createStore, applyMiddleware } from 'redux';&lt;br&gt;
import thunk from 'redux-thunk';&lt;br&gt;
import rootReducer from '../reducers';&lt;br&gt;
export default function configureStore(initialState) {&lt;br&gt;
const enhancer = applyMiddleware(thunk)&lt;br&gt;
return createStore(&lt;br&gt;
rootReducer,&lt;br&gt;
initialState,&lt;br&gt;
enhancer&lt;br&gt;
);&lt;br&gt;
}&lt;br&gt;
`&lt;/code&gt;&lt;br&gt;
Using Redux Thunk in a Sample Application&lt;br&gt;
The most common use case for Redux Thunk is for communicating asynchronously with an external API to retrieve or save data. Redux Thunk makes it easy to dispatch actions that follow the lifecycle of a request to an external API.&lt;br&gt;
showing a list of posts involves first dispatching an action. Then, if the list of post is successfully showed and returned by the external server, then list of posts are shown Otherwise an error message is displayed&lt;br&gt;
Let’s see how this would be accomplished using Redux Thunk.&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;br&gt;
import React, { Component, PropTypes } from 'react';&lt;br&gt;
import { connect } from 'react-redux';&lt;br&gt;
import { ListGroup, ListGroupItem } from 'react-bootstrap';&lt;br&gt;
import { itemsFetchData } from '../actions/items';&lt;br&gt;
class ItemList extends Component {&lt;br&gt;
componentDidMount() {&lt;br&gt;
this.props.fetchData('&lt;a href="https://jsonplaceholder.typicode.com/posts'"&gt;https://jsonplaceholder.typicode.com/posts'&lt;/a&gt;);&lt;br&gt;
}&lt;br&gt;
render() {&lt;br&gt;
if (this.props.hasError) {&lt;br&gt;
return &lt;/p&gt;
&lt;p&gt;Sorry! There was an error loading the items&lt;/p&gt;;&lt;br&gt;
}&lt;br&gt;
if (this.props.isLoading) {&lt;br&gt;
return &lt;p&gt;Loading…&lt;/p&gt;;&lt;br&gt;
}&lt;br&gt;
return (


{this.props.items.map((item) =&amp;gt; (



&lt;span&gt;Body: {item.body}&lt;/span&gt;




&lt;p&gt;))}&lt;br&gt;
&lt;/p&gt;
&lt;br&gt;
);&lt;br&gt;
}&lt;br&gt;
}&lt;br&gt;
var setMargin = {&lt;br&gt;
padding: "0px 200px 20px 200px"&lt;br&gt;
};&lt;br&gt;
var borderNone = {&lt;br&gt;
border: "none",&lt;br&gt;
background: "#fff"&lt;br&gt;
};&lt;br&gt;
var setDistanceBetweenItems = {&lt;br&gt;
marginBottom: "5px",&lt;br&gt;
padding: "30px",&lt;br&gt;
paddingBottom: "50px",&lt;br&gt;
background: "#fff"&lt;br&gt;
};&lt;br&gt;
ItemList.propTypes = {&lt;br&gt;
fetchData: PropTypes.func.isRequired,&lt;br&gt;
items: PropTypes.array.isRequired,&lt;br&gt;
hasError: PropTypes.bool.isRequired,&lt;br&gt;
isLoading: PropTypes.bool.isRequired&lt;br&gt;
};&lt;br&gt;
const mapStateToProps = (state) =&amp;gt; {&lt;br&gt;
return {&lt;br&gt;
items: state.items,&lt;br&gt;
hasError: state.itemsHaveError,&lt;br&gt;
isLoading: state.itemsAreLoading&lt;br&gt;
};&lt;br&gt;
};&lt;br&gt;
const mapDispatchToProps = (dispatch) =&amp;gt; {&lt;br&gt;
return {&lt;br&gt;
fetchData: (url) =&amp;gt; dispatch(itemsFetchData(url))&lt;br&gt;
};&lt;br&gt;
};&lt;br&gt;
export default connect(mapStateToProps, mapDispatchToProps)(ItemList);&lt;br&gt;
&lt;code&gt;&lt;/code&gt;&lt;code&gt;&lt;br&gt;
**Fetching data from an API**&lt;br&gt;
Now onto our application. All of the above code snippets were just examples. We will now dive into the important bits of the code of our app. Also, a github repo will be available at the end of the article, containing the entire app.&lt;br&gt;
Our app will fetch (asynchronously) data that is retrieved by an API — assuming we already built and deployed a working API, how convenient :) — and then display the fetched data as nice as my UI design skills go (not too far).&lt;br&gt;
TVmaze’s public API contains tonnes of data and we will fetch all the shows they have ever aired. Then, the app will display all the shows, toghether with their rating and premiere date.&lt;br&gt;
Designing our state&lt;br&gt;
In order for this application to work properly, our state needs to have 3 properties:&lt;/code&gt;isLoading&lt;code&gt;,&lt;/code&gt;hasError `and items. So we will have one action creator for each property and an extra action creator where we will fetch the data and call the other 3 action creators based on the status of our request to the API.&lt;br&gt;
Action creators

&lt;p&gt;Let’s have a look at the first 3 action creators:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;`&lt;br&gt;
export function itemsHaveError(bool) {&lt;br&gt;
        return {&lt;br&gt;
            type: 'ITEMS_HAVE_ERROR',&lt;br&gt;
            hasError: bool&lt;br&gt;
        };&lt;br&gt;
    }&lt;br&gt;
    export function itemsAreLoading(bool) {&lt;br&gt;
        return {&lt;br&gt;
            type: 'ITEMS_ARE_LOADING',&lt;br&gt;
            isLoading: bool&lt;br&gt;
        };&lt;br&gt;
    }&lt;br&gt;
    export function itemsFetchDataSuccess(items) {&lt;br&gt;
        return {&lt;br&gt;
            type: 'ITEMS_FETCH_DATA_SUCCESS',&lt;br&gt;
            items&lt;br&gt;
        };&lt;br&gt;
    }&lt;br&gt;
`&lt;/code&gt;&lt;br&gt;
The last one will be called after the fetching was successful and will receive the fetched items as an parameter. This action creator will return an object with a property called items that will receive as value the array of items which were passed as an argument. Instead if &lt;code&gt;items&lt;/code&gt;: &lt;code&gt;items&lt;/code&gt;, we can just write items, using an ES6 syntactic sugar called property shorthand.&lt;br&gt;
To visualize a bit what was described earlier, this is how it looks in Redux DevTools:&lt;br&gt;
Out of the box, action creators can return just actions. That’s where Redux Thunk comes in handy. Thunk allows us to have action creators that return a function instead of an action and dispatch an action only in certain cases.&lt;br&gt;
If it wasn’t for Redux Thunk, we would probably end up having just one action creator, something like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;`&lt;br&gt;
export function itemsFetchData(url) {&lt;br&gt;
        const items = axios.get(url);&lt;br&gt;
        return {&lt;br&gt;
            type: 'ITEMS_FETCH_DATA',&lt;br&gt;
            items&lt;br&gt;
        };&lt;br&gt;
    }&lt;br&gt;
`&lt;/code&gt;&lt;br&gt;
Obviously, it would be a lot harder in this scenario to know if the items are still loading or checking if we have an error.&lt;br&gt;
Knowing these and using Redux Thunk, our action creator will be:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;`&lt;br&gt;
export function itemsFetchData(url) {&lt;br&gt;
        return (dispatch) =&amp;gt; {&lt;br&gt;
            dispatch(itemsAreLoading(true));&lt;br&gt;
            axios.get(url)&lt;br&gt;
                .then((response) =&amp;gt; {&lt;br&gt;
                    if (response.status !== 200) {&lt;br&gt;
                        throw Error(response.statusText);&lt;br&gt;
                    }&lt;br&gt;
                    dispatch(itemsAreLoading(false));&lt;br&gt;
                    return response;&lt;br&gt;
                })&lt;br&gt;
                .then((response) =&amp;gt; dispatch(itemsFetchDataSuccess(response.data)))&lt;br&gt;
                .catch(() =&amp;gt; dispatch(itemsHaveError(true)));&lt;br&gt;
        };&lt;br&gt;
    }&lt;br&gt;
`&lt;/code&gt;&lt;br&gt;
Reducers&lt;br&gt;
Now that we have our action creators in place, let’s start writing our reducers.&lt;br&gt;
All reducers will be called when an action is dispatched. Because of this, we are returning the original state in each of our reducers. When the action type matches, the reducer does what it has to do and returns a new slice of state. If not, the reducer returns the original state back.&lt;br&gt;
Each reducer takes 2 parameters: the (soon to be previous) slice of state and an action object:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;`&lt;br&gt;
export function itemsHaveError(state = false, action) {&lt;br&gt;
        switch (action.type) {&lt;br&gt;
            case 'ITEMS_HAVE_ERROR':&lt;br&gt;
                return action.hasError;&lt;br&gt;
            default:&lt;br&gt;
                return state;&lt;br&gt;
        }&lt;br&gt;
    }&lt;br&gt;
    export function itemsAreLoading(state = false, action) {&lt;br&gt;
        switch (action.type) {&lt;br&gt;
            case 'ITEMS_ARE_LOADING':&lt;br&gt;
                return action.isLoading;&lt;br&gt;
            default:&lt;br&gt;
                return state;&lt;br&gt;
        }&lt;br&gt;
    }&lt;br&gt;
    export function items(state = [], action) {&lt;br&gt;
        switch (action.type) {&lt;br&gt;
            case 'ITEMS_FETCH_DATA_SUCCESS':&lt;br&gt;
                return action.items;&lt;br&gt;
            default:&lt;br&gt;
                return state;&lt;br&gt;
        }&lt;br&gt;
    }&lt;br&gt;
`&lt;/code&gt;&lt;br&gt;
Now that we have the reducers created, let’s combine them in our &lt;code&gt;index.js&lt;/code&gt; from our &lt;code&gt;reducers&lt;/code&gt;folder:&lt;/p&gt;

&lt;p&gt;`&lt;code&gt;&lt;/code&gt;&lt;br&gt;
import { combineReducers } from 'redux';&lt;br&gt;
    import { items, itemsHaveError, itemsAreLoading } from './items';&lt;br&gt;
    export default combineReducers({&lt;br&gt;
        items,&lt;br&gt;
        itemsHaveError,&lt;br&gt;
        itemsAreLoading&lt;br&gt;
    });&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;`&lt;/p&gt;

</description>
      <category>react</category>
      <category>redux</category>
    </item>
    <item>
      <title>Understanding Asynchronous Redux Actions with Redux Thunk</title>
      <dc:creator>Famini-ProDev</dc:creator>
      <pubDate>Fri, 22 Apr 2022 13:28:42 +0000</pubDate>
      <link>https://dev.to/faminiprodev/understanding-asynchronous-redux-actions-with-redux-thunk-4g81</link>
      <guid>https://dev.to/faminiprodev/understanding-asynchronous-redux-actions-with-redux-thunk-4g81</guid>
      <description>&lt;p&gt;By default, Redux’s actions are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects. Redux also allows for middleware that sits between an action being dispatched and the action reaching the reducers.&lt;br&gt;
There are two very popular middleware libraries that allow for side effects and asynchronous actions: Redux Thunk and Redux Saga. In this post, you will explore Redux Thunk.&lt;br&gt;
Thunk is a programming concept where a function is used to delay the evaluation/calculation of an operation.&lt;br&gt;
Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions inside the function’s body once the asynchronous operations have been completed.&lt;br&gt;
In this article, you will learn how to add Redux Thunk and how it can fit in a hypothetical Post List application.&lt;br&gt;
.The first step:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adding redux-thunk&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, use the terminal to navigate to the project directory and install the redux-thunk package in your project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install redux-thunk@2.1.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now apply the middleware when creating your app’s store using Redux’s applyMiddleware. Given a React application with redux and react-redux, your &lt;code&gt;configurationStore.js&lt;/code&gt; file might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
export default function configureStore(initialState) {
const enhancer = applyMiddleware(thunk)
return createStore(
rootReducer,
initialState,
enhancer
);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using Redux Thunk in a Sample Application&lt;br&gt;
The most common use case for Redux Thunk is for communicating asynchronously with an external API to retrieve or save data. Redux Thunk makes it easy to dispatch actions that follow the lifecycle of a request to an external API.&lt;br&gt;
showing a list of posts involves first dispatching an action. Then, if the list of post is successfully showed and returned by the external server, then list of posts are shown Otherwise an error message is displayed&lt;br&gt;
Let’s see how this would be accomplished using Redux Thunk.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { ListGroup, ListGroupItem } from 'react-bootstrap';
import { itemsFetchData } from '../actions/items';
class ItemList extends Component {
componentDidMount() {
this.props.fetchData('https://jsonplaceholder.typicode.com/posts');
}
render() {
if (this.props.hasError) {
return &amp;lt;p&amp;gt;Sorry! There was an error loading the items&amp;lt;/p&amp;gt;;
}
if (this.props.isLoading) {
return &amp;lt;p&amp;gt;Loading…&amp;lt;/p&amp;gt;;
}
return (
&amp;lt;div style={setMargin}&amp;gt;
{this.props.items.map((item) =&amp;gt; (
&amp;lt;div key={item.id}&amp;gt;
&amp;lt;ListGroup style={setDistanceBetweenItems}&amp;gt;
&amp;lt;ListGroupItem style={borderNone} header={item.title}&amp;gt;
&amp;lt;span className="pull-xs-right"&amp;gt;Body: {item.body}&amp;lt;/span&amp;gt;
&amp;lt;/ListGroupItem&amp;gt;
&amp;lt;/ListGroup&amp;gt;
&amp;lt;/div&amp;gt;
))}
&amp;lt;/div&amp;gt;
);
}
}
var setMargin = {
padding: "0px 200px 20px 200px"
};
var borderNone = {
border: "none",
background: "#fff"
};
var setDistanceBetweenItems = {
marginBottom: "5px",
padding: "30px",
paddingBottom: "50px",
background: "#fff"
};
ItemList.propTypes = {
fetchData: PropTypes.func.isRequired,
items: PropTypes.array.isRequired,
hasError: PropTypes.bool.isRequired,
isLoading: PropTypes.bool.isRequired
};
const mapStateToProps = (state) =&amp;gt; {
return {
items: state.items,
hasError: state.itemsHaveError,
isLoading: state.itemsAreLoading
};
};
const mapDispatchToProps = (dispatch) =&amp;gt; {
return {
fetchData: (url) =&amp;gt; dispatch(itemsFetchData(url))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ItemList);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Fetching data from an API&lt;/strong&gt;&lt;br&gt;
Now onto our application. All of the above code snippets were just examples. We will now dive into the important bits of the code of our app. Also, a github repo will be available at the end of the article, containing the entire app.&lt;br&gt;
Our app will fetch (asynchronously) data that is retrieved by an API — assuming we already built and deployed a working API, how convenient :) — and then display the fetched data as nice as my UI design skills go (not too far).&lt;br&gt;
TVmaze’s public API contains tonnes of data and we will fetch all the shows they have ever aired. Then, the app will display all the shows, toghether with their rating and premiere date.&lt;br&gt;
Designing our state&lt;br&gt;
In order for this application to work properly, our state needs to have 3 properties: &lt;code&gt;isLoading&lt;/code&gt;, &lt;code&gt;hasError&lt;/code&gt;and items. So we will have one action creator for each property and an extra action creator where we will fetch the data and call the other 3 action creators based on the status of our request to the API.&lt;br&gt;
Action creators&lt;/p&gt;

&lt;p&gt;Let’s have a look at the first 3 action creators:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export function itemsHaveError(bool) {
        return {
            type: 'ITEMS_HAVE_ERROR',
            hasError: bool
        };
    }
    export function itemsAreLoading(bool) {
        return {
            type: 'ITEMS_ARE_LOADING',
            isLoading: bool
        };
    }
    export function itemsFetchDataSuccess(items) {
        return {
            type: 'ITEMS_FETCH_DATA_SUCCESS',
            items
        };
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The last one will be called after the fetching was successful and will receive the fetched items as an parameter. This action creator will return an object with a property called items that will receive as value the array of items which were passed as an argument. Instead if &lt;code&gt;items&lt;/code&gt;: &lt;code&gt;items&lt;/code&gt;, we can just write items, using an ES6 syntactic sugar called property shorthand.&lt;br&gt;
To visualize a bit what was described earlier, this is how it looks in Redux DevTools:&lt;br&gt;
Out of the box, action creators can return just actions. That’s where Redux Thunk comes in handy. Thunk allows us to have action creators that return a function instead of an action and dispatch an action only in certain cases.&lt;br&gt;
If it wasn’t for Redux Thunk, we would probably end up having just one action creator, something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export function itemsFetchData(url) {
        const items = axios.get(url);
        return {
            type: 'ITEMS_FETCH_DATA',
            items
        };
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Obviously, it would be a lot harder in this scenario to know if the items are still loading or checking if we have an error.&lt;br&gt;
Knowing these and using Redux Thunk, our action creator will be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export function itemsFetchData(url) {
        return (dispatch) =&amp;gt; {
            dispatch(itemsAreLoading(true));
            axios.get(url)
                .then((response) =&amp;gt; {
                    if (response.status !== 200) {
                        throw Error(response.statusText);
                    }
                    dispatch(itemsAreLoading(false));
                    return response;
                })
                .then((response) =&amp;gt; dispatch(itemsFetchDataSuccess(response.data)))
                .catch(() =&amp;gt; dispatch(itemsHaveError(true)));
        };
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Reducers&lt;br&gt;
Now that we have our action creators in place, let’s start writing our reducers.&lt;br&gt;
All reducers will be called when an action is dispatched. Because of this, we are returning the original state in each of our reducers. When the action type matches, the reducer does what it has to do and returns a new slice of state. If not, the reducer returns the original state back.&lt;br&gt;
Each reducer takes 2 parameters: the (soon to be previous) slice of state and an action object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export function itemsHaveError(state = false, action) {
        switch (action.type) {
            case 'ITEMS_HAVE_ERROR':
                return action.hasError;
            default:
                return state;
        }
    }
    export function itemsAreLoading(state = false, action) {
        switch (action.type) {
            case 'ITEMS_ARE_LOADING':
                return action.isLoading;
            default:
                return state;
        }
    }
    export function items(state = [], action) {
        switch (action.type) {
            case 'ITEMS_FETCH_DATA_SUCCESS':
                return action.items;
            default:
                return state;
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have the reducers created, let’s combine them in our &lt;code&gt;index.js&lt;/code&gt; from our &lt;code&gt;reducers&lt;/code&gt;folder:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { combineReducers } from 'redux';
    import { items, itemsHaveError, itemsAreLoading } from './items';
    export default combineReducers({
        items,
        itemsHaveError,
        itemsAreLoading
    });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Creating the store&lt;br&gt;
Don’t forget about including the Redux Thunk middleware in the &lt;code&gt;configureStore.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createStore, applyMiddleware } from 'redux';
    import thunk from 'redux-thunk';
    import rootReducer from '../reducers';
    export default function configureStore(initialState) {
        const composeEnhancers = 
            window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   
                window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
                    // options like actionSanitizer, stateSanitizer
                }) : compose;
        const enhancer = composeEnhancers(
            applyMiddleware(thunk)
        );
        return createStore(
            rootReducer,
            initialState,
            enhancer
        );
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the store in our root &lt;code&gt;index.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
    import { render } from 'react-dom';
    import { Provider } from 'react-redux';
    import configureStore from './store/configureStore';
    import ItemList from './components/ItemList';
    const store = configureStore();
    render(
        &amp;lt;Provider store={store}&amp;gt;
            &amp;lt;ItemList /&amp;gt;
        &amp;lt;/Provider&amp;gt;,
        document.getElementById('app')
    );

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Writing our React component which shows the fetched data&lt;br&gt;
Let’s start by talking about what we are importing here.&lt;br&gt;
In order to work with Redux, we have to import &lt;code&gt;connect&lt;/code&gt;from 'react-redux':&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { connect } from 'react-redux';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also, because we will fetch the data in this component, we will import our action creator that fetches data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { itemsFetchData } from '../actions/items';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are importing only this action creator, because this one also dispatches the other actions to the store.&lt;br&gt;
Next step would be to map the state to the components’ props. For this, we will write a function that receives &lt;code&gt;state&lt;/code&gt;and returns the props object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mapStateToProps = (state) =&amp;gt; {
        return {
            items: state.items,
            hasError: state.itemsHaveError,
            isLoading: state.itemsAreLoading
        };
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we have a new &lt;code&gt;state&lt;/code&gt;, the &lt;code&gt;props&lt;/code&gt;in our component will change according to our new state.&lt;br&gt;
Also, we need to dispatch our imported action creator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mapDispatchToProps = (dispatch) =&amp;gt; {
        return {
            fetchData: (url) =&amp;gt; dispatch(itemsFetchData(url))
        };
    };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this one, we have access to our &lt;code&gt;itemFetchData&lt;/code&gt;action creator through our &lt;code&gt;props&lt;/code&gt;object. This way, we can call our action creator by doing &lt;br&gt;
&lt;code&gt;this.props.fetchData(url);&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
Now, in order to make these methods actually do something, when we export our component, we have to pass these methods as arguments to &lt;code&gt;connect&lt;/code&gt;. This connects our component to Redux.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default connect(mapStateToProps, mapDispatchToProps)(ItemList);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, we will call this action creator in the &lt;code&gt;componentDidMount&lt;/code&gt; lifecycle method:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;this.props.fetchData('https://jsonplaceholder.typicode.com/posts');&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Besides this, we need some validations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (this.props.hasError) {
        return &amp;lt;p&amp;gt;Sorry! There was an error loading the items&amp;lt;/p&amp;gt;;
    }
    if (this.props.isLoading) {
        return &amp;lt;p&amp;gt;Loading ...&amp;lt;/p&amp;gt;;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the actual iteration over our fetched data array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{this.props.items.map((item) =&amp;gt; (
        // display data here
    ))}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the end, our component will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component, PropTypes } from 'react';
    import { connect } from 'react-redux';
    import { ListGroup, ListGroupItem } from 'react-bootstrap';
    import { itemsFetchData } from '../actions/items';
    class ItemList extends Component {
        componentDidMount() {
            this.props.fetchData('https://jsonplaceholder.typicode.com/posts');
        }
        render() {
            if (this.props.hasError) {
                return &amp;lt;p&amp;gt;Sorry! There was an error loading the items&amp;lt;/p&amp;gt;;
            }
            if (this.props.isLoading) {
                return &amp;lt;p&amp;gt;Loading ...&amp;lt;/p&amp;gt;;
            }
            return (
                &amp;lt;div style={setMargin}&amp;gt;
                    {this.props.items.map((item) =&amp;gt; (
                        &amp;lt;div key={item.id}&amp;gt;
                                &amp;lt;ListGroup style={setDistanceBetweenItems}&amp;gt;
                                    &amp;lt;ListGroupItem  header={item.title}&amp;gt;
                                        &amp;lt;span className="pull-xs-right"&amp;gt;Body: {item.body}&amp;lt;/span&amp;gt;
                                    &amp;lt;/ListGroupItem&amp;gt;
                                &amp;lt;/ListGroup&amp;gt;
                        &amp;lt;/div&amp;gt;
                    ))}
                &amp;lt;/div&amp;gt;
            );
        }
    }
    ItemList.propTypes = {
        fetchData: PropTypes.func.isRequired,
        items: PropTypes.array.isRequired,
        hasError: PropTypes.bool.isRequired,
        isLoading: PropTypes.bool.isRequired
    };
    const mapStateToProps = (state) =&amp;gt; {
        return {
            items: state.items,
            hasError: state.itemsHaveError,
            isLoading: state.itemsAreLoading
        };
    };
    const mapDispatchToProps = (dispatch) =&amp;gt; {
        return {
            fetchData: (url) =&amp;gt; dispatch(itemsFetchData(url))
        };
    };
    export default connect(mapStateToProps, mapDispatchToProps)(ItemList);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that was all !&lt;/p&gt;

&lt;p&gt;You can see the full source of this project in : &lt;a href="https://github.com/Famini-ProDev/PostList-redux-thunk"&gt;https://github.com/Famini-ProDev/PostList-redux-thunk&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>redux</category>
    </item>
  </channel>
</rss>
