<?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: Jeet Bhalani</title>
    <description>The latest articles on DEV Community by Jeet Bhalani (@je_et15).</description>
    <link>https://dev.to/je_et15</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%2F826592%2F7428da9b-52c4-4bca-828a-782321a17f00.png</url>
      <title>DEV Community: Jeet Bhalani</title>
      <link>https://dev.to/je_et15</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/je_et15"/>
    <language>en</language>
    <item>
      <title>Getting Started with NextAuth.js: Authentication for Next.js</title>
      <dc:creator>Jeet Bhalani</dc:creator>
      <pubDate>Mon, 10 Mar 2025 07:27:33 +0000</pubDate>
      <link>https://dev.to/je_et15/getting-started-with-nextauthjs-authentication-for-nextjs-33nc</link>
      <guid>https://dev.to/je_et15/getting-started-with-nextauthjs-authentication-for-nextjs-33nc</guid>
      <description>&lt;p&gt;Authentication is a must-have for most web apps, and NextAuth.js makes it incredibly easy to set up authentication in a Next.js project. Whether you're using OAuth providers like GitHub and Google, or custom credentials, NextAuth.js has you covered.&lt;/p&gt;

&lt;p&gt;In this guide, I'll walk you through setting up NextAuth.js from scratch and share some tips to make your authentication flow seamless.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is NextAuth.js?
&lt;/h2&gt;

&lt;p&gt;NextAuth.js is a flexible authentication library built for Next.js. It supports multiple authentication strategies, including:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;OAuth (Google, GitHub, Twitter, etc.)&lt;/li&gt;
&lt;li&gt;Credentials-based authentication (email/password, magic links, etc.)&lt;/li&gt;
&lt;li&gt;JWT (JSON Web Tokens) for secure, stateless authentication&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With minimal setup, you can add authentication to your Next.js app without handling user sessions manually.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting Up NextAuth.js
&lt;/h2&gt;

&lt;p&gt;1️⃣ Install NextAuth.js&lt;br&gt;
Run the following command to install NextAuth.js in your Next.js 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 next-auth
# or
yarn add next-auth

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

&lt;/div&gt;



&lt;p&gt;2️⃣ Create an API Route&lt;br&gt;
NextAuth.js requires an API route to handle authentication. Create a new file at pages/api/auth/[...nextauth].ts (or .js if you're not using TypeScript) and add the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import NextAuth from "next-auth";
import GitHubProvider from "next-auth/providers/github";

export default NextAuth({
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    async session({ session, token }) {
      session.user.id = token.sub;
      return session;
    },
  },
});

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;We're using GitHub as the authentication provider.&lt;/li&gt;
&lt;li&gt;The API route handles login and logout flows.&lt;/li&gt;
&lt;li&gt;We're modifying the session object to include the user ID.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;3️⃣ Set Up Environment Variables.&lt;br&gt;
To keep your API keys secure, create a .env.local file in the root directory and add:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
NEXTAUTH_URL=http://localhost:3000

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;NextAuth.js uses environment variables to securely store API keys.&lt;/li&gt;
&lt;li&gt;NEXTAUTH_URL ensures OAuth redirects work correctly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;4️⃣ Implement Authentication in a Component.&lt;br&gt;
Now, let’s add login and logout functionality to a React component using the useSession hook from next-auth/react:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useSession, signIn, signOut } from "next-auth/react";

export default function AuthButton() {
  const { data: session } = useSession();

  if (session) {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;p&amp;gt;Welcome, {session.user.name}&amp;lt;/p&amp;gt;
        &amp;lt;button onClick={() =&amp;gt; signOut()}&amp;gt;Sign Out&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
  return &amp;lt;button onClick={() =&amp;gt; signIn("github")}&amp;gt;Sign In with GitHub&amp;lt;/button&amp;gt;;
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;If the user is logged in, we show their name and a sign-out button.&lt;/li&gt;
&lt;li&gt;If not, we display a Sign In with GitHub button.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;5️⃣ Protecting Pages with Authentication.&lt;br&gt;
If you want to restrict access to certain pages (e.g., a dashboard), you can use getServerSideProps to check the session:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { getSession } from "next-auth/react";

export async function getServerSideProps(context) {
  const session = await getSession(context);

  if (!session) {
    return {
      redirect: {
        destination: "/api/auth/signin",
        permanent: false,
      },
    };
  }
  return { props: { session } };
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;It ensures that only authenticated users can access the page.&lt;/li&gt;
&lt;li&gt;Unauthenticated users are redirected to the sign-in page.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  🎯 Wrapping Up
&lt;/h2&gt;

&lt;p&gt;With just a few steps, we've integrated NextAuth.js into a Next.js project. This setup works for both OAuth providers (GitHub, Google, etc.) and custom authentication strategies.&lt;/p&gt;

&lt;p&gt;🔥 Next Steps&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Add more authentication providers like Google or Twitter.&lt;/li&gt;
&lt;li&gt;Customize user sessions with database integration.&lt;/li&gt;
&lt;li&gt;Explore NextAuth.js callbacks and events for advanced use cases.&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>Getting Started with Next.js: A Simple Guide</title>
      <dc:creator>Jeet Bhalani</dc:creator>
      <pubDate>Sun, 09 Feb 2025 08:05:45 +0000</pubDate>
      <link>https://dev.to/je_et15/getting-started-with-nextjs-a-simple-guide-2nk2</link>
      <guid>https://dev.to/je_et15/getting-started-with-nextjs-a-simple-guide-2nk2</guid>
      <description>&lt;p&gt;Next.js is a powerful React framework that simplifies building fast, scalable web applications. With built-in features like server-side rendering (SSR), static site generation (SSG), and API routes, it provides a great developer experience.&lt;/p&gt;

&lt;p&gt;In this quick guide, we’ll set up a Next.js project, explore its core features, and build a simple page.&lt;/p&gt;

&lt;h2&gt;
  
  
  📌 Prerequisites
&lt;/h2&gt;

&lt;p&gt;✅ Node.js installed (recommended: v18+)&lt;br&gt;
✅ Basic knowledge of React.js&lt;/p&gt;
&lt;h2&gt;
  
  
  🚀 Step 1: Setting Up a Next.js Project
&lt;/h2&gt;

&lt;p&gt;To create a new Next.js project, run the following command in your terminal:&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-next-app@latest my-next-app
cd my-next-app
npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This starts a development server at &lt;code&gt;http://localhost:3000.&lt;/code&gt; 🎉&lt;/p&gt;

&lt;h2&gt;
  
  
  📂 Step 2: Understanding the Project Structure
&lt;/h2&gt;

&lt;p&gt;A new Next.js project includes:&lt;/p&gt;

&lt;p&gt;📁 pages/ – Each file here becomes a route (e.g., index.js → /)&lt;br&gt;
📁 public/ – Stores static assets (images, icons, etc.)&lt;br&gt;
📁 styles/ – Contains global styles and CSS modules&lt;/p&gt;
&lt;h2&gt;
  
  
  🛠️ Step 3: Creating a Page
&lt;/h2&gt;

&lt;p&gt;Each file inside the pages/ directory automatically becomes a route. Let’s create an About page:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// pages/about.js
export default function About() {
  return &amp;lt;h1&amp;gt;About Page&amp;lt;/h1&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Visit &lt;code&gt;http://localhost:3000/about&lt;/code&gt; to see it in action!&lt;/p&gt;

&lt;h2&gt;
  
  
  🎨 Step 4: Styling in Next.js.
&lt;/h2&gt;

&lt;p&gt;Next.js supports global CSS, CSS Modules, and Tailwind CSS.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using CSS Modules:
&lt;/h2&gt;

&lt;p&gt;Create a CSS file inside the &lt;code&gt;styles/&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;/* styles/Home.module.css */
.title {
  color: blue;
  font-size: 24px;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Import it inside a page:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import styles from '../styles/Home.module.css';

export default function Home() {
  return &amp;lt;h1 className={styles.title}&amp;gt;Hello Next.js&amp;lt;/h1&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  🔄 Step 5: Fetching Data in Next.js
&lt;/h2&gt;

&lt;p&gt;Next.js provides multiple ways to fetch data:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;getStaticProps (SSG) – Fetches data at build time&lt;/li&gt;
&lt;li&gt;getServerSideProps (SSR) – Fetches data on every request&lt;/li&gt;
&lt;li&gt;useEffect (CSR) – Fetches data on the client side&lt;/li&gt;
&lt;li&gt;Example using getStaticProps:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export async function getStaticProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  const posts = await res.json();

  return {
    props: { posts },
  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method pre-renders the page with fetched data.&lt;/p&gt;

&lt;h2&gt;
  
  
  🚀 Step 6: Deploying Next.js
&lt;/h2&gt;

&lt;p&gt;You can deploy your Next.js app easily using Vercel (the creators of Next.js).&lt;/p&gt;

&lt;p&gt;To deploy:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Push your project to GitHub&lt;/li&gt;
&lt;li&gt;Go to Vercel and import your repo&lt;/li&gt;
&lt;li&gt;Click Deploy 🎉&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  🎯 Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Next.js is an excellent choice for modern web development, offering SEO benefits, fast performance, and easy routing. Start building your first project today!&lt;/p&gt;

&lt;p&gt;🚀 What’s next? Explore:&lt;/p&gt;

&lt;p&gt;🔹 API Routes in Next.js&lt;br&gt;
🔹 Middleware &amp;amp; Authentication&lt;br&gt;
🔹 Server Actions &amp;amp; Optimizations.&lt;/p&gt;

&lt;p&gt;Happy coding! 💻✨&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Wanna copy Data Objects? Shallow copy And Deep copy are the ways: In JS</title>
      <dc:creator>Jeet Bhalani</dc:creator>
      <pubDate>Sun, 22 May 2022 17:30:20 +0000</pubDate>
      <link>https://dev.to/je_et15/wanna-copy-data-objects-shallow-copy-and-deep-copy-is-the-way-in-js-d75</link>
      <guid>https://dev.to/je_et15/wanna-copy-data-objects-shallow-copy-and-deep-copy-is-the-way-in-js-d75</guid>
      <description>&lt;p&gt;__In JavaScript, Data can be divided into two main categories which are &lt;code&gt;primitive&lt;/code&gt;data types and &lt;code&gt;reference&lt;/code&gt; data types. The word data here refers to all the collection of Array, strings and objects which are mostly used to store data in js.&lt;/p&gt;

&lt;p&gt;If you don't know what are they no worries here's a link to get some more knowledge ____&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;1.&lt;/code&gt; Primitive data types:
&lt;/h2&gt;

&lt;p&gt;The value assigned to a primitive data type variable is strongly tied. This means that anytime you replicate a basic data type variable, the value is transferred to a new &lt;code&gt;memory address&lt;/code&gt; that the new variable points to. It will be a true copy if you make a copy.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;2.&lt;/code&gt; Reference data types:
&lt;/h2&gt;

&lt;p&gt;Whereas, for reference data type it stores the address of the memory location where the object is stored. There are two types of copying reference data types namely &lt;code&gt;shallow copy&lt;/code&gt; and &lt;code&gt;deep copy&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Shallow copy:
&lt;/h2&gt;

&lt;p&gt;A shallow copy just points to the reference address of the original collection structure (object or array) that carries the value in the new variable; that is, only the collection structure is copied, not the element.&lt;/p&gt;

&lt;p&gt;When the field value is a reference type it just copies the reference address, no new object will be created. The referenced objects are thus shared.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let Obj1 = {name: "apple", type: "fruit"};
let clonedObj = obj1;
clonedObj.name = ‘orange’;

// Output:
clonedObj = {name: “orange”, type: “fruit”}
obj1 = {name: “orange”, type: “fruit”}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Shallow copy is simple and typically cheap, as they can be usually implemented by simply copying the reference address. Similarly, this can be observed for arrays.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = [1,2,3];
let clonedArr = arr;
clonedArr.push(4);

// Output:
clonedArr = [1,2,3,4]
arr = [1,2,3,4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, there are methods for copying objects without referencing them.&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;code&gt;1.&lt;/code&gt; Spread operator (…)
&lt;/h1&gt;

&lt;p&gt;It is a convenient way to make a shallow copy of an array or object —when there is no nesting, it works great.&lt;/p&gt;

&lt;p&gt;It is useful for creating new instances of arrays that do not behave unexpectedly due to old references.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let Obj1 = {name: "apple"};
let clonedObj = {...obj1};
clonedObj.name = ‘orange’;

// Output:
clonedObj = {name: “orange”}
obj1 = {name: “apple”}

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

&lt;/div&gt;



&lt;h1&gt;
  
  
  &lt;code&gt;2.&lt;/code&gt; Object.assign().
&lt;/h1&gt;

&lt;p&gt;It copies enumerable properties from a source object to a target object. Further, this can be used only if the object/array contains primitive type values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let Obj1 = {name: "apple"};
let clonedObj = Object.assign({}, obj1);
clonedObj.name = ‘orange’;

// Output:
clonedObj = {name: “orange”}
obj1 = {name: “apple”}

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

&lt;/div&gt;



&lt;h1&gt;
  
  
  &lt;code&gt;3.&lt;/code&gt; Slice().
&lt;/h1&gt;

&lt;p&gt;For arrays specifically, using the built-in .slice() method works the same as the spread operator — creating a shallow copy of one level:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = [1,2,3,4,5]
let clonedArr = arr.slice();
clonedArr.push(6);

//Output:
arr = [1, 2, 3, 4, 5]
clonedArr = [1, 2, 3, 4, 5, 6]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  &lt;code&gt;4.&lt;/code&gt; Array.from().
&lt;/h1&gt;

&lt;p&gt;Another method to copy a JavaScript array is using Array.from()which will also make a shallow copy.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = [1,2,3,4,5]
let clonedArr = Array.from(arr);
clonedArr.push(6);

// Output:
arr = [1, 2, 3, 4, 5]
clonedArr = [1, 2, 3, 4, 5, 6]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These techniques will copy up to the first level. Because nested objects are not truly cloned, the internally copied reference type value for any nested object or array will refer to its memory address, causing shallow copies to operate unexpectedly. To overcome this, we must iterate and copy until we reach the final level, whereas this method is costly and not recommended. A deep copy will be required for objects that are deeply nested.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deep copy
&lt;/h2&gt;

&lt;p&gt;It simply creates a duplicate of all the properties of the source object into the target object. In other words, both the primitive type and reference type properties will be allocated to new memory locations.&lt;/p&gt;

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

&lt;p&gt;The correct term to use would be cloning, where you know that they both are totally the same, but yet different (i.e. stored as two different entities in the memory space).&lt;/p&gt;

&lt;p&gt;It is used to copy JavaScript objects to a new variable NOT by reference.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const nestedArray = [["4"] ,["9"] ,["7"]];

const nestedCopyWithSpread = [...nestedArray];

console.log(nestedArray[0] === nestedCopyWithSpread[0]); 
// true -- Shallow copy (same reference)

const nestedCopyWithJSON = JSON.parse(JSON.stringify(nestedArray));

console.log(nestedArr[0] === nestedCopyWithJSON[0]);
// false -- Deep copy (different references)

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

&lt;/div&gt;



&lt;p&gt;The strict equality operator &lt;code&gt;(===)&lt;/code&gt;shows that the nested references are the same for shallow copy and different for deep copy.&lt;/p&gt;

&lt;p&gt;There are many methods of making a deep copy (or deep clone):&lt;/p&gt;

&lt;h1&gt;
  
  
  &lt;code&gt;1.&lt;/code&gt; JSON.parse/stringify.
&lt;/h1&gt;

&lt;p&gt;It helps in parsing a stringified Object and vice versa.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
let originalObj = {name: “apple”, price: {chennai: 120}};

let clonedObj = JSON.parse(JSON.stringify(originalObj));
clonedObj.name =”orange”;

clonedObj.price.chennai = “34”;

// Output:
clonedObj = {name: “orange”, price: {chennai: 100}}
originalObj = {name: “apple”, price: {chennai: 34}}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  &lt;code&gt;2.&lt;/code&gt; Lodash.
&lt;/h1&gt;

&lt;p&gt;It is a JavaScript library that provides multiple utility functions and one of the most commonly used functions of the Lodash library is the cloneDeep() method. This method helps in the deep cloning of an object and also clones the non-serializable properties which were a limitation in the JSON.stringify() approach.&lt;/p&gt;

&lt;p&gt;Of the various copy algorithms, the shallow copies are the fastest, followed by deep copies using a custom function &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In JavaScript, it's actually quite simple to avoid having to deep copy if you never nest objects and arrays inside each other. Because in that scenario — where there is no layering and the objects and arrays just contain primitive values — producing a shallow copy using the spread operator (...),.slice(), and.assign() all function perfectly.&lt;/p&gt;

&lt;p&gt;However, in the actual world, where objects contain arrays or vice versa, a deep copy will be required.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>objects</category>
      <category>coding</category>
      <category>webdev</category>
    </item>
    <item>
      <title>A ReactJS Hook : useState()</title>
      <dc:creator>Jeet Bhalani</dc:creator>
      <pubDate>Thu, 19 May 2022 08:12:02 +0000</pubDate>
      <link>https://dev.to/je_et15/a-reactjs-hook-usestate-25bb</link>
      <guid>https://dev.to/je_et15/a-reactjs-hook-usestate-25bb</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuhettzsp2zvfxwch558a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuhettzsp2zvfxwch558a.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
 &lt;strong&gt;useState&lt;/strong&gt; is a Hook that enables state variables to be used in functional components. This function takes the initial state and returns a variable with the current state value and another function to update it.&lt;/p&gt;

&lt;p&gt;In React, there are two type of components class based and functional based. Functional components are simple functions that accept parameters as component properties and return valid JSX:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function React(props) {
  return &amp;lt;div&amp;gt;{props.useState}&amp;lt;/div&amp;gt;
}
// Or as an arrow function
const React = (props) =&amp;gt;  &amp;lt;div&amp;gt;{props.useState}&amp;lt;/div&amp;gt;

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

&lt;/div&gt;



&lt;p&gt;There are no state or lifecycle methods, as you can see. &lt;/p&gt;

&lt;p&gt;React Hooks are the functions that add state variables to functional components. They usually begin with the keyword &lt;strong&gt;&lt;em&gt;use&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use &lt;code&gt;useState&lt;/code&gt; Hook in ReactJS? What does it do?
&lt;/h2&gt;

&lt;p&gt;useState allows you to add state to function components, as previously indicated. When you use useState inside a function component, it creates a single piece of state for that component.&lt;/p&gt;

&lt;p&gt;Whereas in a class, the state is always an object, Hooks' state can be any type. Each state item contains a single value, which can be an object, an array, a boolean, or any other kind you can think of.&lt;/p&gt;

&lt;p&gt;So, when is it appropriate to utilize the useState Hook? It's particularly effective for the local component state, but larger projects may require the usage of additional state management methods.&lt;/p&gt;

&lt;h2&gt;
  
  
  Declaring&lt;code&gt;{ useState }&lt;/code&gt;in your React App.
&lt;/h2&gt;

&lt;p&gt;To use the UseState hook in your App simply type the following code:&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, { useState } from 'react';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;useState&lt;/code&gt; Hook allows you to declare only one state variable (of any type) at a time, 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, { useState } from 'react';

const React= () =&amp;gt; {
   const message = useState( '' );
   const listOfMessage = useState( [] );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;useState&lt;/code&gt;takes the initial value of the state variable as an argument.&lt;/p&gt;

&lt;p&gt;You can pass it directly, as shown in the previous example, or use a function to initialize the variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Message= () =&amp;gt; {
   const message = useState( () =&amp;gt; helloWorld() );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The initial value will only be assigned on the first render and if it's a function, it will only be called on the first render.&lt;/p&gt;

&lt;p&gt;The initial parameter of the useState Hook will be ignored in subsequent renders (due to a change of state in the component or a parent component) and the current value will be obtained.&lt;/p&gt;

&lt;p&gt;Because its argument is only used for the first time — not every time the property changes — using useState alone won't work.&lt;/p&gt;

&lt;p&gt;However, unlike the previous examples, useState does not just return a variable.&lt;/p&gt;

&lt;p&gt;It returns an array with the state variable as the first element and a function to update the variable's value as the second element.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Array destructuring&lt;/code&gt;is commonly used to simplify the code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const React= () =&amp;gt; {
   const [message, setMessage]= useState( '' );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Updating the &lt;code&gt;useState&lt;/code&gt; in React Hooks
&lt;/h2&gt;

&lt;p&gt;The second element returned by &lt;code&gt;useState&lt;/code&gt; is a function that updates the state variable with a new value.&lt;/p&gt;

&lt;p&gt;Here's an example of how to update the state variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const React = () =&amp;gt; {
  const [message, setMessage] = useState( '' );

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;input
         type="text"
         value={message}
         placeholder="Enter a text"
         onChange={e =&amp;gt; setMessage(e.target.value)}
       /
  &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This update function, on the other hand, does not immediately update the value.&lt;/p&gt;

&lt;p&gt;  The &lt;code&gt;useState&lt;/code&gt; parameter will be ignored after re-rendering the component, and this function will return the most recent value or the new state values.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using state varibales as an object: In &lt;code&gt;useState()&lt;/code&gt; Hooks
&lt;/h2&gt;

&lt;p&gt;If we add another property to the message object (id) like in the previous example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const React = () =&amp;gt; {
  const [messageObj, setMessage] = useState({ message: '', id: 1 });

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;input
        type="text"
        value={messageObj.message}
        placeholder="Enter a message"
        onChange={e =&amp;gt; {
          const newMessageObj = { message: e.target.value };
          setMessage(newMessageObj); 
        }}
      /&amp;gt;
      &amp;lt;p&amp;gt;
        &amp;lt;strong&amp;gt;{messageObj.id} : {messageObj.message}&amp;lt;/strong&amp;gt;
      &amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And we only update the&lt;code&gt;message&lt;/code&gt;property like in the above example, React will replace the original state object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ message: '', id: 1 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the object used in the &lt;code&gt;onChange&lt;/code&gt; event, which only contains the message property:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ message: 'message entered' } // id property is lost
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You may replicate the behavior of setState() by passing the object to be replaced as a function argument and using the object &lt;code&gt;spread&lt;/code&gt; syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;onChange={e =&amp;gt; {
  const val = e.target.value;
  setMessage(prevState =&amp;gt; {
    return { ...prevState, message: val }
  });
}}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;...prevState&lt;/code&gt; part will get all of the properties of the object and the &lt;code&gt;message: value&lt;/code&gt; part will overwrite the &lt;code&gt;message&lt;/code&gt;property.&lt;/p&gt;

&lt;p&gt;You just have to be careful when applying the &lt;code&gt;spread&lt;/code&gt;syntax to multidimensional arrays because it won’t work as you might expect.&lt;/p&gt;

&lt;p&gt;This leads us to another thing to consider when working with objects as the state.&lt;/p&gt;

&lt;h2&gt;
  
  
  Updating state in React hooks: For Nested objects
&lt;/h2&gt;

&lt;p&gt;In JavaScript, multidimensional arrays are arrays within arrays:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
  ['value1','value2'],
  ['value3','value4']
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You could use them to centralize all of your state variables. However, it is preferable to use nested objects for this purpose:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  'row1' : {
    'key1' : 'value1',
    'key2' : 'value2'
  },
  'row2' : {
    'key3' : 'value3',
    'key4' : 'value4'
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, when working with multidimensional arrays and nested objects, the &lt;code&gt;spread&lt;/code&gt; syntax and &lt;code&gt;Object. assign&lt;/code&gt; will create a shallow copy rather than a deep copy.&lt;/p&gt;

&lt;p&gt;When copying an array, the &lt;code&gt;spread&lt;/code&gt;syntax essentially goes one level deep. As a result, as the following example shows, it may not be suited for copying multidimensional arrays. (The same is true for &lt;code&gt;spread&lt;/code&gt; syntax and &lt;code&gt;Object.assign()&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;let a = [[1], [2], [3]];
let b = [...a];

b.shift().shift(); //  1
//  Array 'a' is affected as well: [[], [2], [3]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;but the important point is that when using nested objects, we can’t just use the spread syntax to update the state object.&lt;/p&gt;

&lt;p&gt;For example, consider the following state 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 [msgObj, setMsg] = useState({
  author: '',
  msg: {
    id: 1,
    text: ''
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The following code snippets show some incorrect ways to update the text field:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Wrong
setMsg(prevState =&amp;gt; ({
  ...prevState,
  text: 'My message'
}));

// Wrong
setMsg(prevState =&amp;gt; ({
  ...prevState.msg,
  text: 'My message'
}));

// Wrong
setMsg(prevState =&amp;gt; ({
  ...prevState,
  msg: {
    text: 'My message'
  }
}));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To properly update the text field, we have to copy to a new object the entire set of fields/nested objects of the original object&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Correct
setMsg(prevState =&amp;gt; ({
  ...prevState,      
  msg: {             
    ...prevState.msg, 
    text: 'My message'    
  }
}));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the same way, here’s how you’d update the author field of the state object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Correct
setMsg(prevState =&amp;gt; ({
  author: 'Joe',      
  ...prevState.msg  
}));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Assuming the message object doesn’t change. If it does change, you’d have to update the object this way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Correct
setMsg(prevState =&amp;gt; ({
  author: 'Joe',         
  msg: {              
    ...prevState.msg, 
    text: 'My message'    
  }
}));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conculsion
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;useState&lt;/code&gt; is a Hook (function) that enables state variables to be used in functional components. This function takes the initial state and returns a variable with the current state value (not necessarily the starting state) and another function to update it.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>react</category>
    </item>
    <item>
      <title>Async Js let's Make It Happen With Promises</title>
      <dc:creator>Jeet Bhalani</dc:creator>
      <pubDate>Thu, 19 May 2022 08:07:11 +0000</pubDate>
      <link>https://dev.to/je_et15/async-js-lets-make-it-happen-with-promises-5gh6</link>
      <guid>https://dev.to/je_et15/async-js-lets-make-it-happen-with-promises-5gh6</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8oeet9iiljjtcf5xb3yg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8oeet9iiljjtcf5xb3yg.png" alt="Image description" width="728" height="360"&gt;&lt;/a&gt;Promises are asynchronous computations that represent operations that are yet to be complete.&lt;/p&gt;

&lt;p&gt;Having you here means you know some basic knowledge about javascript &amp;amp; How it works synchronously. If you don't no worries here are some links to &lt;/p&gt;

&lt;h2&gt;
  
  
  Promise terminology
&lt;/h2&gt;

&lt;p&gt;A promise is a JavaScript object that allows you to make asynchronous(aka async) calls. It produces a value when the async operation completes successfully or produces an error if it doesn't complete.&lt;/p&gt;

&lt;p&gt;A promise can be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;fulfilled&lt;/strong&gt; - The action relating to the promise succeeded.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;rejected&lt;/strong&gt; - The action relating to the promise failed.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;pending&lt;/strong&gt; - Hasn't fulfilled or rejected yet.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;settled&lt;/strong&gt; - Has fulfilled or rejected.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Although promise implementations follow a standardized behavior, their overall APIs differ. JavaScript promises are similar in API to RSVP.js. Here's how you create a promise:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const promise = new Promise(function(resolve, reject)=&amp;gt;{
  // do a thing, possibly async, then…

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Step 1.&lt;/code&gt;&lt;br&gt;
The promise constructor takes one argument, a callback with two parameters, &lt;code&gt;resolve&lt;/code&gt; and &lt;code&gt;reject&lt;/code&gt;. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Step 2.&lt;/code&gt;&lt;br&gt;
The resolve method indicates successful completion of the task(fetching water), and the reject method indicates an error(the disaster). You do not implement the resolve/reject method. JavaScript provides it to you. You need to call them from the executor function.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Step 3.&lt;/code&gt;&lt;br&gt;
so here an example of resolved promise :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Creating a promise
let promise = new Promise(function(resolve, reject) {
    resolve("resolved"); // resloved on success
});

// Consuming a promise
promise.then((value) =&amp;gt; console.log(value)) // resloved


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

&lt;/div&gt;



&lt;p&gt;so here as you can see to know what exactly a promise is returning after creating a promise we use &lt;code&gt;.then()&lt;/code&gt; and we can say it as consuming a promise.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Step 4.&lt;/code&gt;&lt;br&gt;
so here an example of rejected promise :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Creating a promise
let promise = new Promise(function(resolve, reject) {
    reject("rejected"); // rejected on failure
});

// Consuming a promise
promise.then((value) =&amp;gt; console.log(value)) // rejected


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

&lt;/div&gt;



&lt;p&gt;here promise is rejected so it logs out rejected on failure&lt;/p&gt;

&lt;h2&gt;
  
  
  Promise States and Object
&lt;/h2&gt;

&lt;p&gt;The promise object should be capable of informing the consumers when the execution has been started, completed (resolved), or returned with an error (rejected).&lt;/p&gt;

&lt;p&gt;A promise object has the following internal properties,&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;state&lt;/strong&gt;: This property can have the following values,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;pending:&lt;/code&gt; When the execution function starts.  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;fulfilled:&lt;/code&gt; When the promise resolves successfully. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;rejected:&lt;/code&gt; When the promise rejects. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;result:&lt;/strong&gt; This property can have the following values,&lt;br&gt;
undefined: Initially, when the state value is pending.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;value:&lt;/code&gt; When the promise is resolved(value).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;error:&lt;/code&gt; When the promise is rejected.&lt;br&gt;
A promise that is either resolved or rejected is called settled.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

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

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp8ation9g5hua45vy7i7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp8ation9g5hua45vy7i7.png" alt="Image description" width="321" height="157"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;`&lt;/p&gt;
&lt;h2&gt;
  
  
  Handling Promises by the Consumers
&lt;/h2&gt;

&lt;p&gt;The promise object returned by the new Promise constructor has it all. A consumer can use it to know the state(pending, fulfilled, or rejected) and the possible outcomes(value or error) from it.&lt;/p&gt;

&lt;p&gt;But hold on. These properties are internal. They are code-inaccessible, but they are inspectable. It means that we will be able to inspect the state and result property values using a debugger tool, but we will not be able to access them directly using the program.&lt;/p&gt;

&lt;p&gt;So then? That's where we have three important handler methods, .then(), .catch(), and .finally(). These methods help us create a link between the executor and the consumer when a promise resolves or rejects.&lt;/p&gt;
&lt;h2&gt;
  
  
  The &lt;code&gt;.then()&lt;/code&gt; Promise Handler
&lt;/h2&gt;

&lt;p&gt;We get a .then() method from every promise. The sole purpose of this method is to let the consumer know about the outcome of a promise. It accepts two functions as arguments, result and error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;promise.then(
  (result) =&amp;gt; { 
     console.log(result);
  },
  (error) =&amp;gt; { 
     console.log(error);
  }
);

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

&lt;/div&gt;



&lt;p&gt;If you are just interested in the successful outcome, you can chose to pass only one argument,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;promise.then(
  (result) =&amp;gt; { 
      console.log(result);
  }
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similarly, if you are interested in only the error, pass null as the value for the first argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;promise.then(
  null,
  (error) =&amp;gt; { 
      console.log(error)
  }
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also note, you can do three very exceptional things inside the &lt;code&gt;.then()&lt;/code&gt; method,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You can &lt;code&gt;return&lt;/code&gt; another promise from it.&lt;/li&gt;
&lt;li&gt;You can &lt;code&gt;return&lt;/code&gt; a value including undefined.&lt;/li&gt;
&lt;li&gt;You can &lt;code&gt;throw&lt;/code&gt; an error.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These three points will be the basis of learning the Promise Chain which is a whole new advance topic and will cover it in the future blog.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// 1. Creating a Promise

let promise = new Promise(function(resolve, reject) {
 // Pretend a delay of 2 sec to fetch it!
  setTimeout(function() {
      // Let's resolve the promise
      resolve('resolved promise');
  }, 2000);
});


// now let us consume promise
const consumePromise = () =&amp;gt; {
  // The handler function to handle the resolved promise
  promise.then(function(result) {
    console.log(`Consumed ${result}`);
  });
}

// 3. Calling the function 
consumePromise();

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

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;output // Consumed resolved promise
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The &lt;code&gt;.catch()&lt;/code&gt; Promise Handler
&lt;/h2&gt;

&lt;p&gt;You can use this handler method to handle errors (rejections) from promises.As we discussed already, it is a much better syntax to handle the error situation than handling it using the .then() method.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.catch()&lt;/code&gt; helps to handle the failure of API calls and handle errors.Here in catch its takes argument which shows the error by consoling it. &lt;br&gt;
using .catch() to handle errors&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// 1. Create the promise
let promise = new Promise(function(resolve, reject) {
  reject("rejected") // rejected  
}

promise.then((value)=&amp;gt;console.log(value))
.catch((error)=&amp;gt;console.log(error))

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  The &lt;code&gt;.finally()&lt;/code&gt;Promise Handler
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;.finally()&lt;/code&gt; handler method performs cleanups like stopping a loader, closing a live connection, and so on. Irrespective of whether a promise resolves or rejects, the .finally() method will be called.&lt;br&gt;
Here &lt;code&gt;.finally()&lt;/code&gt; takes a callback function as argument&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// 1. Create the promise
const isLoading = true;
let promise = new Promise(function(resolve, reject) {
  reject("rejected") // rejected  
}

promise.then((value)=&amp;gt;console.log(value))
.catch((error)=&amp;gt;console.log(error))
.finally(()=&amp;gt;{
isLoading = false
})

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;To Summarize,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Promise is an important building block for the asynchronous concept in JavaScript.&lt;/li&gt;
&lt;li&gt;You can create a promise using the constructor function.&lt;/li&gt;
&lt;li&gt;The constructor accepts an executor function as an argument and returns a promise object.&lt;/li&gt;
&lt;li&gt;A promise object has two internal properties, state and result. These properties are not code-accessible.&lt;/li&gt;
&lt;li&gt;The consumer of a promise can use the .then(), .catch(), and .finally() methods to handle promises.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>asyncjs</category>
      <category>promises</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
