<?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>Forem: Husnain Mustafa</title>
    <description>The latest articles on Forem by Husnain Mustafa (@husnain).</description>
    <link>https://forem.com/husnain</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%2F915326%2F2729e59b-d9b7-4e31-a3ec-1bb7c517b977.jpg</url>
      <title>Forem: Husnain Mustafa</title>
      <link>https://forem.com/husnain</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/husnain"/>
    <language>en</language>
    <item>
      <title>CAP theorem</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Sun, 06 Apr 2025 01:46:27 +0000</pubDate>
      <link>https://forem.com/husnain/cap-theorem-apo</link>
      <guid>https://forem.com/husnain/cap-theorem-apo</guid>
      <description>&lt;p&gt;The CAP theorem, where C stands for Consistency, A for Availability, and P for Partition Tolerance, states that in a distributed system, it is impossible to guarantee all three properties simultaneously. A system can achieve at most two out of the three at any given time. Let's go through each of these terms to better understand the theorem.&lt;/p&gt;

&lt;h2&gt;
  
  
  CAP
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Consistency
&lt;/h3&gt;

&lt;p&gt;Consistency ensures that every request to the system receives the most up-to-date and valid data, meaning that once a data update occurs, all subsequent requests will see the updated data. It guarantees that the data provided is not stale.&lt;/p&gt;

&lt;h3&gt;
  
  
  Availability
&lt;/h3&gt;

&lt;p&gt;Availability refers to a system being operational and responsive at all times, even if some of its nodes are not working. Nodes could refer to different components of the system or to full replicas of the system, which are often managed behind a load balancer to distribute traffic.&lt;/p&gt;

&lt;h3&gt;
  
  
  Partition Tolerance
&lt;/h3&gt;

&lt;p&gt;Partition Tolerance means the system can continue to operate and handle requests even if network partitions occur, meaning some nodes or parts of the system are unable to communicate with each other. It guarantees that the system will remain functional despite disruptions in network connectivity between nodes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Distributed System
&lt;/h2&gt;

&lt;p&gt;A Distributed System is a network of independent computers or nodes that work together to achieve a common goal, often appearing as a single system to users. These nodes collaborate to handle tasks like data storage, processing, and request handling, but they operate in different locations and may communicate over a network.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why CAP theorem exist?
&lt;/h2&gt;

&lt;p&gt;The CAP theorem applies specifically to distributed systems. Imagine a system with nodes distributed across multiple geographical locations. In such a system, network partitions can occur, leading to Partition Tolerance. As a result, the system must choose between Consistency or Availability.&lt;/p&gt;

&lt;p&gt;The reason for this limitation is that if the system prioritizes Consistency (i.e., ensuring data is up-to-date), it requires communication between nodes to synchronize data. This process takes time, during which the system may be unavailable, thereby affecting Availability.&lt;/p&gt;

&lt;p&gt;On the other hand, if the system prioritizes Availability, it might allow data to become inconsistent by ignoring the latest updates. This keeps the system available without waiting for data synchronization, but it sacrifices Consistency, as different nodes may have outdated or conflicting data.&lt;/p&gt;

&lt;p&gt;To achieve both Availability and Consistency, the system would need to avoid network partitions, meaning nodes must be able to communicate without delay. However, this would sacrifice Partition Tolerance, as the system could fail to operate properly in the event of network issues.&lt;/p&gt;

</description>
      <category>distributedsystems</category>
      <category>systemdesign</category>
      <category>architecture</category>
    </item>
    <item>
      <title>Deploy ComfyUI with RunPod Serverless</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Tue, 22 Oct 2024 07:02:23 +0000</pubDate>
      <link>https://forem.com/husnain/deploy-comfyui-with-runpod-serverless-1i25</link>
      <guid>https://forem.com/husnain/deploy-comfyui-with-runpod-serverless-1i25</guid>
      <description>&lt;p&gt;What is ComfyUI? ComfyUI, according to &lt;a href="https://github.com/comfyanonymous/ComfyUI" rel="noopener noreferrer"&gt;author&lt;/a&gt;, "lets you design and execute advanced stable diffusion pipelines using a graph/nodes/flowchart based interface". Basically, we can play with stable diffusion pipelines by just moving around some nodes.&lt;/p&gt;

&lt;p&gt;So what is stable diffusion? Its a GenAI (Generative Artificial Intelligence) which can generate images from text prompts, images or both.&lt;/p&gt;

&lt;p&gt;Before moving on, let's understand what is Runpod. Execution of an AI model need to take place in GPU (Graphic Processing Unit) as it allows millions of tiny processing unit, working at the &lt;em&gt;same time&lt;/em&gt;. And GPUs are costly. So rather than buying GPU and running the models locally, we can rent out the GPU service from services like RunPod. RunPod provides us the cloud service for developing and executing AI models.&lt;/p&gt;

&lt;p&gt;RunPod allows us 2 types of services, Pods and Serverless. Pods are the services that keep on, no matter whether the required service / API is being used or not. Where as in serverless provide workers, which only works when needed, and hence charged less (only for the time worker is).&lt;/p&gt;

&lt;p&gt;Now let's dive into deploying ComfyUI with RunPod.&lt;/p&gt;

&lt;h2&gt;
  
  
  Runpod Worker Comfy
&lt;/h2&gt;

&lt;p&gt;We are going to use &lt;a href="https://github.com/blib-la/runpod-worker-comfy" rel="noopener noreferrer"&gt;runpod-worker-comfy&lt;/a&gt; for the deployment. &lt;br&gt;
Although the git repo has detailed explanation for Comfy deployment, I had to face some issues which may stuck you if you doing this for the first time. &lt;/p&gt;

&lt;p&gt;We do not need to clone this repo, rather we are going to use the docker images provided by runpod worker comfy.&lt;/p&gt;

&lt;p&gt;Runpod worker comfy provides us 5 images as follow:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;timpietruskyblibla/runpod-worker-comfy:3.1.0-base: doesn't contain anything, just a clean ComfyUI&lt;/li&gt;
&lt;li&gt;timpietruskyblibla/runpod-worker-comfy:3.1.0-flux1-schnell: contains the checkpoint, text encoders and VAE for FLUX.1 schnell&lt;/li&gt;
&lt;li&gt;timpietruskyblibla/runpod-worker-comfy:3.1.0-flux1-dev: contains the checkpoint, text encoders and VAE for FLUX.1 dev&lt;/li&gt;
&lt;li&gt;timpietruskyblibla/runpod-worker-comfy:3.1.0-sdxl: contains the checkpoint and VAE for Stable Diffusion XL&lt;/li&gt;
&lt;li&gt;timpietruskyblibla/runpod-worker-comfy:3.1.0-sd3: contains the checkpoint for Stable Diffusion 3 medium&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Dockerfile
&lt;/h2&gt;

&lt;p&gt;Based on your requirement, select one of the image.&lt;br&gt;
We can use the selected image as raw, or we can add some customised layers, like adding packages or custom nodes (custom nodes can be added in the network volume, discussed later). In my case, I had to use a package &lt;code&gt;rembg[gpu]&lt;/code&gt;, need to remove the background from a given image. So here is my updated Dockerfile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM timpietruskyblibla/runpod-worker-comfy:3.1.0-sd3
RUN pip install rembg[gpu]
CMD /start.sh
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For adding custom nodes, you can do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
RUN git clone &amp;lt;custom_node_repo.git&amp;gt; /comfyui/custom_nodes
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now build an image by &lt;code&gt;docker build &amp;lt;dockerhub-username&amp;gt;/&amp;lt;your-image-name&amp;gt;&lt;/code&gt;. Once done, push the image to docker hub by &lt;code&gt;docker image push &amp;lt;dockerhub-username&amp;gt;/&amp;lt;your-image-name&amp;gt;&lt;/code&gt;. You can use Docker GUI to push your image to docker hub.&lt;/p&gt;

&lt;p&gt;You may skip the above steps if you do not need any customisation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Runpod
&lt;/h2&gt;

&lt;p&gt;Now we need to configure our runpod.&lt;/p&gt;

&lt;h4&gt;
  
  
  Storage
&lt;/h4&gt;

&lt;p&gt;Let's make a Network Volume, which will have our output images, custom nodes (if we haven't added those using Dockerfile) and custom models.&lt;/p&gt;

&lt;p&gt;Go to &lt;code&gt;Storage&lt;/code&gt; in sidebar. Click on &lt;code&gt;New Network Volume&lt;/code&gt;, select the data center, volume name and the storage volume it holds.&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%2Fvph9xtksd514h5pv3q30.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%2Fvph9xtksd514h5pv3q30.png" alt=" " width="800" height="575"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can select any data center, usually the one which supports the cheapest (and medium - highly available) GPU, as GPU would only be required to deploy the instance. Won't affect the image processing.&lt;/p&gt;

&lt;p&gt;For storage volume, it depends upon your requirements. How much space is required by custom models and custom nodes. If you are not using any custom models/nodes, I think 10GB is fine.&lt;/p&gt;

&lt;p&gt;Once the network volume is created, we need to deploy it temporarily to make it accessible so we can add the custom things. &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%2Fm8a6th8oxzuoeb1e47ho.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%2Fm8a6th8oxzuoeb1e47ho.png" alt=" " width="800" height="502"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Select any of the GPU, select GPU count as 1, and select instance pricing as &lt;code&gt;Spot&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Once network volume is deployed, go to &lt;code&gt;Pods&lt;/code&gt; in side bar and you will a see a newly listed Pod. Click on it and connect the terminal through web.&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%2F0yd4lmkdll49sh3ptgi6.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%2F0yd4lmkdll49sh3ptgi6.png" alt=" " width="800" height="785"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now you will see the terminal interface in web. We need to place everything in &lt;code&gt;workspace&lt;/code&gt; directory because its the directory of volume and contains persistent data. Anything not in this directory will be removed as soon as we delete the deployed instance of Network Volume.&lt;br&gt;
So go to /workspace by &lt;code&gt;cd workspace&lt;/code&gt; and make respective directories i.e for custom nodes, make &lt;code&gt;custom_nodes&lt;/code&gt; by command &lt;code&gt;mkdir custom_nodes&lt;/code&gt;. Move into &lt;code&gt;custom_nodes&lt;/code&gt; by &lt;code&gt;cd custom_nodes&lt;/code&gt; and clone your desired nodes from git by &lt;code&gt;git clone &amp;lt;repo url&amp;gt;&lt;/code&gt;.&lt;br&gt;
Once you are done with adding custom nodes, exit the terminal by &lt;code&gt;exit&lt;/code&gt; and close your web terminal tab. &lt;/p&gt;

&lt;h4&gt;
  
  
  Serverless Deployment of Comfy
&lt;/h4&gt;

&lt;p&gt;Now head over to &lt;code&gt;Serverless&lt;/code&gt; in sidebar and click on &lt;code&gt;New Endpoint&lt;/code&gt;. The below screen will shown&lt;br&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%2F22kayupd2m1pgjfzafu0.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%2F22kayupd2m1pgjfzafu0.png" alt=" " width="800" height="576"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We have to provide our configurations. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Select GPU&lt;/li&gt;
&lt;li&gt;Enter you &lt;code&gt;Endpoint Name&lt;/code&gt;, this could be anything&lt;/li&gt;
&lt;li&gt;For &lt;code&gt;Worker Configuration&lt;/code&gt; section, you should go through these &lt;a href="https://github.com/blib-la/runpod-worker-comfy?tab=readme-ov-file#create-your-endpoint" rel="noopener noreferrer"&gt;docs&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;For container configuration, leave &lt;code&gt;Template&lt;/code&gt; and &lt;code&gt;Container Registry Credentials&lt;/code&gt; as empty. 
Enter the container image as the image you chose from the runpod-worker-comfy &lt;code&gt;timpietruskyblibla/runpod-worker-comfy:3.1.0-&amp;lt;your model&amp;gt;&lt;/code&gt; like &lt;code&gt;timpietruskyblibla/runpod-worker-comfy:3.1.0-sd3&lt;/code&gt;
For &lt;code&gt;Container Start Command&lt;/code&gt;, write: &lt;code&gt;sh -c "ln -sf /runpod-volume/custom_nodes/* /comfyui/custom_nodes &amp;amp;&amp;amp; /start.sh"&lt;/code&gt;. This command makes a symlink between comfyui directory and network volume workspace. You may also link other directories too.
&lt;strong&gt;Note&lt;/strong&gt;: You can skip the above container start command if you haven't installed any custom nodes, models or any other custom stuff. If so, leave this field empty.&lt;/li&gt;
&lt;li&gt;For Container Disk, it should be more than 20GB.&lt;/li&gt;
&lt;li&gt;Leave HTTP and TCP ports empty&lt;/li&gt;
&lt;li&gt;For Environment Variables, enter these:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;BUCKET_ENDPOINT_URL --- for endpoint of s3 i.e https://bucket.s3.region.amazonaws.com

BUCKET_ACCESS_KEY_ID --- for access key of s3
BUCKET_SECRET_ACCESS_KEY --- for secret key of s3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Keep the advance sections as itself.&lt;/li&gt;
&lt;li&gt;Finally deploy your serverless instance.&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Creating API Key
&lt;/h4&gt;

&lt;p&gt;Now to access your deployed instance, you would require an API key. Which you can get by:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Go to &lt;code&gt;Settings&lt;/code&gt; in sidebar&lt;/li&gt;
&lt;li&gt;Create new API Key, enter any desired name, select its access i.e &lt;code&gt;only read&lt;/code&gt; or &lt;code&gt;read &amp;amp; write&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Copy the generated API Key and store it somewhere safe.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Using comfy
&lt;/h2&gt;

&lt;p&gt;Let's test if our comfy works as expected. But before moving on, we need the API endpoint where we are going to request. &lt;br&gt;
Go to &lt;code&gt;Serverless&lt;/code&gt; in sidebar and click on the instance you just deployed. It will be like this:&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%2Fcnnzkwsruez91gkvcpya.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%2Fcnnzkwsruez91gkvcpya.png" alt=" " width="800" height="534"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can access the logs in case of debugging. For now, we need API endpoint which you will see at the bottom of image. We got 5 different routes. You may read the guide &lt;a href="https://docs.runpod.io/serverless/references/operations" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You can either go with &lt;code&gt;run&lt;/code&gt; or &lt;code&gt;runsync&lt;/code&gt; to get result by accessing &lt;code&gt;status&lt;/code&gt; or getting result immediately, respectively. In most cases, comfy takes some time so its better to go with &lt;code&gt;run&lt;/code&gt; and check the &lt;code&gt;status&lt;/code&gt; after some interval.&lt;/p&gt;

&lt;h4&gt;
  
  
  API Request
&lt;/h4&gt;

&lt;p&gt;You may read the docs of API Request Format &lt;a href="https://github.com/blib-la/runpod-worker-comfy?tab=readme-ov-file#json-request-body" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;br&gt;
Once workflow is created you can request the above mentioned API Endpoint with API Key in header by &lt;code&gt;Bearer &amp;lt;API Key&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  API Response for /run
&lt;/h4&gt;

&lt;p&gt;It will return &lt;code&gt;id&lt;/code&gt; of the job, at the root of response body. You will use this id to check the status of of job by /status/&lt;/p&gt;

&lt;h4&gt;
  
  
  API Response for /status
&lt;/h4&gt;

&lt;p&gt;It will return the &lt;code&gt;status&lt;/code&gt; of the job, at the root of response body, along with &lt;code&gt;output&lt;/code&gt; if status is &lt;code&gt;COMPLETED&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;All Done, now you can make another layer of API which will may only take desired inputs and return the output of comfy by checking the &lt;code&gt;status&lt;/code&gt; at some intervals.&lt;/p&gt;

&lt;p&gt;That's all. Happy learning❤️&lt;/p&gt;

</description>
      <category>comfy</category>
      <category>runpod</category>
      <category>serverless</category>
      <category>s3</category>
    </item>
    <item>
      <title>What are CORS? and how to configure it in Node?</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Mon, 13 May 2024 21:35:21 +0000</pubDate>
      <link>https://forem.com/husnain/what-are-cors-and-how-to-configure-it-in-node-4c3n</link>
      <guid>https://forem.com/husnain/what-are-cors-and-how-to-configure-it-in-node-4c3n</guid>
      <description>&lt;p&gt;  &lt;iframe src="https://www.youtube.com/embed/y2HNjC2et5E"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;CORS, Cross-origin resource sharing, is a policy implemented by the browsers. &lt;/p&gt;

&lt;h3&gt;
  
  
  Origin
&lt;/h3&gt;

&lt;p&gt;First, let's understand what is origin. Origin is made up of the &lt;code&gt;base url&lt;/code&gt; and the &lt;code&gt;port&lt;/code&gt;. So &lt;code&gt;https://abc.com&lt;/code&gt;, &lt;code&gt;https://abc.com:4040&lt;/code&gt; and &lt;code&gt;https://cba.com&lt;/code&gt; are different origins. Note that when we do not provide a port number with &lt;code&gt;&amp;lt;url&amp;gt;:&amp;lt;port&amp;gt;&lt;/code&gt;, the default port for &lt;code&gt;https&lt;/code&gt; is &lt;code&gt;443&lt;/code&gt; and for &lt;code&gt;http&lt;/code&gt;, its &lt;code&gt;80&lt;/code&gt;. Hence, in the above example of &lt;code&gt;https://abc.com&lt;/code&gt;, we have a port of &lt;code&gt;443&lt;/code&gt; by default.&lt;/p&gt;

&lt;h3&gt;
  
  
  Cross origin
&lt;/h3&gt;

&lt;p&gt;Cross origin simply means that one origin is trying to connect to another origin.&lt;/p&gt;

&lt;h3&gt;
  
  
  Cross origin resource sharing
&lt;/h3&gt;

&lt;p&gt;For developing web applications, there are several architecture. &lt;/p&gt;

&lt;p&gt;One of the ways to develop web application is to have the &lt;code&gt;Frontend&lt;/code&gt; and &lt;code&gt;Backend&lt;/code&gt; at the &lt;code&gt;same origin&lt;/code&gt;, for example a NextJs Application, which is responsible for both, Frontend and Backend. In this case, whenever Frontend makes a network request to Backend, it requests on the &lt;code&gt;same origin&lt;/code&gt;. And hence no CORS policy is implemented by browsers.&lt;/p&gt;

&lt;p&gt;Other way to develop web application is to have &lt;code&gt;Frontend&lt;/code&gt; and &lt;code&gt;Backend&lt;/code&gt; at different origins. Let's say we got Frontend, React Application, at port &lt;code&gt;5173&lt;/code&gt;, vite default port. And Backend, Node application, at port &lt;code&gt;3000&lt;/code&gt;. In this case, we got different origins. And hence whenever a network request is made from React app to Node app, browser will implement CORS policy and possibly throwing an error:&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%2F36v6yhfatc0yhon0c63b.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%2F36v6yhfatc0yhon0c63b.png" alt=" " width="800" height="62"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Network Flow
&lt;/h3&gt;

&lt;p&gt;Let's understand what happens, when a cross-origin network call is made.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Client side (Frontend) sends a &lt;code&gt;preflight&lt;/code&gt; request to Server (Backend). &lt;/li&gt;
&lt;li&gt;Server responds with whether the Client side's origin is allowed to request the Server or not. If server allows such origin, the &lt;code&gt;response headers&lt;/code&gt; have the attribute &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; with value of origin / origin pattern.&lt;/li&gt;
&lt;li&gt;Browser check the response headers and verify if its origin matches the origin pattern against the attribute of &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt;. 
 a. If it does matches, browser re-request the server with 
    the actual payload and executes the required network 
    call.
 b. If it does not matches, browser throws an error.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Configuring backend to support CORS
&lt;/h3&gt;

&lt;p&gt;Now we know that to configure CORS, we only need to modify our &lt;code&gt;response headers&lt;/code&gt; to have the attribute of &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; which matches the origin pattern of the client.&lt;/p&gt;

&lt;p&gt;One way of configuring CORS, is by simply using the package, &lt;code&gt;cors&lt;/code&gt; and use the middleware provided by cors&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;cors&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;cors&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;express&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;cors&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;origin&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;http://localhost:5173&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;}));&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Hello World&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Server is running on port 3000&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

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

&lt;/div&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%2Fulue6emmc1juhzqb25pq.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%2Fulue6emmc1juhzqb25pq.png" alt=" " width="800" height="118"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we got everything working, but there is another way of configuring response header, that is without using any package. &lt;/p&gt;

&lt;p&gt;We simply need to define our custom middleware that modifies the response object. Here is how we can achieve it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;express&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;use&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;header&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Access-Control-Allow-Origin&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;http://localhost:5173&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Hello World&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Server is running on port 3000&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: After the changes, you might not see the expected results, try using incognito or clear site cache.&lt;/p&gt;

&lt;p&gt;That's all folks.&lt;br&gt;
Happy coding ❤️&lt;/p&gt;

</description>
      <category>cors</category>
      <category>node</category>
      <category>backenddevelopment</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Debug Typescript using Node Runtime Environment in VS Code</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Thu, 18 Apr 2024 00:46:11 +0000</pubDate>
      <link>https://forem.com/husnain/debug-typescript-using-node-runtime-environment-in-vs-code-ik0</link>
      <guid>https://forem.com/husnain/debug-typescript-using-node-runtime-environment-in-vs-code-ik0</guid>
      <description>&lt;p&gt;  &lt;iframe src="https://www.youtube.com/embed/EPN3wu8sBfk"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;Today, we will learn how we can debug typescript using node runtime environment in VSCode.&lt;/p&gt;

&lt;h3&gt;
  
  
  Typescript Compilation
&lt;/h3&gt;

&lt;p&gt;So to begin debugging, we need to understand how typescript is files are run by Node. Well actually, Node is not able to run typescript files directly. So we need to transpile typescript files into javascript files and then Node runs those transpiled javascript files. To transpile typescript files, we can use &lt;code&gt;tsc&lt;/code&gt;, &lt;code&gt;typescript compiler&lt;/code&gt;.  &lt;/p&gt;

&lt;p&gt;To transpile/compile typescript file into javascript files, we need to define some configuration in the root folder of project in &lt;code&gt;tsconfig.json&lt;/code&gt; file. Here is the very basic &lt;code&gt;tsconfig.json&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"compilerOptions"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"rootDir"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"src"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"outDir"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"dist"&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"sourceMap"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In above json, we have:&lt;br&gt;
&lt;strong&gt;rootDir&lt;/strong&gt;, that tells tsc where are our application files.&lt;br&gt;
&lt;strong&gt;ourDir&lt;/strong&gt;, that tells tsc where tsc need to make transpiled javascript files.&lt;br&gt;
&lt;strong&gt;sourceMap&lt;/strong&gt;, that tells tsc to linkup transpiled javascript files with typescript files. This link is necessary for debugging, so that node debugger show you the typescript file but actually debugging the linked transpiled javascript file.&lt;/p&gt;

&lt;p&gt;Now you can run the command &lt;code&gt;npx tsc&lt;/code&gt; and see the output directory &lt;code&gt;dist&lt;/code&gt; in your project. &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%2Fdx2i5gw24w4faeocpcdq.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%2Fdx2i5gw24w4faeocpcdq.png" alt=" " width="706" height="170"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So now we know how typescript files are actually run by Node. Let's move to next step.&lt;/p&gt;
&lt;h3&gt;
  
  
  VS Code Configuration
&lt;/h3&gt;

&lt;p&gt;Now we need to configure VS Code so whenever we want to debug, it runs a set of commands before debugging.&lt;br&gt;
We need to create &lt;code&gt;launch.json&lt;/code&gt;, a configuration file for VS Code, in the root of the project and have these configurations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"version"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"0.2.0"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"configurations"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"node"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"request"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"launch"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"Debug TS Files"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"program"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"${workspaceFolder}/src/app.ts"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"skipFiles"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"&amp;lt;node_internals&amp;gt;/**"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"preLaunchTask"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"npm: build"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"sourceMaps"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"outFiles"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"${workspaceFolder}/dist/**/*.js"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;version&lt;/strong&gt; simply defines the version of this file.&lt;br&gt;
&lt;strong&gt;configuration&lt;/strong&gt; is an array of objects where each object represent configuration of respective command.&lt;br&gt;
&lt;strong&gt;type&lt;/strong&gt;, type of configuration.&lt;br&gt;
&lt;strong&gt;request&lt;/strong&gt; can either be &lt;code&gt;launch&lt;/code&gt; or &lt;code&gt;attach&lt;/code&gt;. Launch is for launching the app from the start and then attaching debugger. Attach is for attaching debugger on already running app. You can read more &lt;a href="https://code.visualstudio.com/docs/editor/debugging#_launch-versus-attach-configurations" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
&lt;strong&gt;program&lt;/strong&gt; is the base file of your project, in this project's case, its &lt;code&gt;/src/app.ts&lt;/code&gt;.&lt;br&gt;
&lt;strong&gt;skipFiles&lt;/strong&gt; is to skip file while debugging.&lt;br&gt;
&lt;strong&gt;preLaunchTask&lt;/strong&gt; is to do something, like building or transpiling TS files, before launching the debugger.&lt;br&gt;
&lt;strong&gt;sourceMaps&lt;/strong&gt; is to tell VS Code that we are not using project TS files, rather we are using transpiled JS files.&lt;br&gt;
&lt;strong&gt;outFiles&lt;/strong&gt; provides the location of transpiled JS files, which is &lt;code&gt;/dist/**/*.js&lt;/code&gt; in our case, as we provided in the &lt;code&gt;tsconfig.json&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now when you save this file, and go to &lt;code&gt;Run and Debug&lt;/code&gt; tab of VS Code, looks like: &lt;br&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%2F0xr3pf3ged6mbem0ebqh.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%2F0xr3pf3ged6mbem0ebqh.png" alt=" " width="104" height="132"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can see our newly added command at the top: &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%2F4ier1zlyz52f7pvmfzaq.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%2F4ier1zlyz52f7pvmfzaq.png" alt=" " width="734" height="80"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We are almost done.&lt;/p&gt;
&lt;h3&gt;
  
  
  Add build command in package json
&lt;/h3&gt;

&lt;p&gt;If you notice, in &lt;code&gt;launch.json&lt;/code&gt;, we have a configuration:&lt;br&gt;
&lt;code&gt;preLaunchTask: 'npm: build'&lt;/code&gt;&lt;br&gt;
this runs the command &lt;code&gt;npm run build&lt;/code&gt; before attaching a debugger. But we haven't specified this command in package.json yet.&lt;br&gt;
So open your &lt;code&gt;package.json&lt;/code&gt; and add the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="nl"&gt;"scripts"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;...other&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;commands&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"build"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"tsc"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here build is simply running &lt;code&gt;tsc&lt;/code&gt;, which will transpile our TS files in JS files and store those in &lt;code&gt;/dist&lt;/code&gt; (as provided in &lt;code&gt;tsconfig.json&lt;/code&gt;) and our debugger use those sourceMapped files to debug TS files.&lt;/p&gt;

&lt;h3&gt;
  
  
  Run Debugger
&lt;/h3&gt;

&lt;p&gt;Now add breakpoints wherever you want and run debugger by simply clicking play button beside our VS Code command in &lt;code&gt;Run &amp;amp; Debug&lt;/code&gt; tab:&lt;br&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%2F4ier1zlyz52f7pvmfzaq.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%2F4ier1zlyz52f7pvmfzaq.png" alt=" " width="734" height="80"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Congrats! we have our debugger running successfully:&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%2F53uw2ywvj70jebt1qbpn.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%2F53uw2ywvj70jebt1qbpn.png" alt=" " width="800" height="253"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;PS: We can skip all these configuration and use Bun runtime environment to debug as it provides TS debugging out of the box&lt;/p&gt;

&lt;p&gt;Hope you learned something today. &lt;br&gt;
Happy Coding ❤️&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>debug</category>
      <category>node</category>
      <category>vscode</category>
    </item>
    <item>
      <title>Why we cant use await inside forEach? and its workaround.</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Sat, 13 Jan 2024 20:39:36 +0000</pubDate>
      <link>https://forem.com/husnain/why-we-cant-use-await-inside-foreach-and-its-workaround-417i</link>
      <guid>https://forem.com/husnain/why-we-cant-use-await-inside-foreach-and-its-workaround-417i</guid>
      <description>&lt;p&gt;Have you ever tried using the await inside forEach?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;[].&lt;/span&gt;&lt;span class="nf"&gt;forEach&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;async&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;doSomethingWith&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Well I have, when I didn't know much about async/await and forEach. But didn't have the expected result. To understand this, we must first understand how async/await works.&lt;/p&gt;

&lt;h3&gt;
  
  
  How async/await works:
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;async/await&lt;/code&gt; is the another way of doing &lt;code&gt;.then&lt;/code&gt; on the Promises. So whenever an async function reaches the statement where await is used and Promise is yet to be resovled, that function is then runs separately from the parent function, unless we use await on the child function. Let me give you an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;functionA&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Starting Function A&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;300&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;});&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Ending Function A&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;1&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nf"&gt;functionA&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;2&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="nf"&gt;myFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code logs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1
Starting Function A
2
Ending Function A
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You see, first &lt;code&gt;1&lt;/code&gt; is logged, and then we go inside functionA, logs &lt;code&gt;Starting Function A&lt;/code&gt; and as soon as we hit &lt;code&gt;await&lt;/code&gt; keyword, &lt;code&gt;functionA&lt;/code&gt; runs separately and &lt;code&gt;myFunction&lt;/code&gt; moves on and logs &lt;code&gt;2&lt;/code&gt; and finally when our promise resolves in 300 ms, we get the log of &lt;code&gt;Ending Function A&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Lets give it another try with using await on functionA:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;functionA&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Starting Function A&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;300&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;});&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Ending Function A&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;1&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;functionA&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;2&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="nf"&gt;myFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we get the logs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1
Starting Function A
Ending Function A
2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, we must complete the execution of functionA to move on. But you notice that out &lt;code&gt;myFunction&lt;/code&gt; also becomes async. So it will also runs separately from parent function or global scope.&lt;/p&gt;

&lt;p&gt;Let's log another thing just after calling &lt;code&gt;myFunction&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;functionA&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Starting Function A&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;300&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;});&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Ending Function A&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;1&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;functionA&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;2&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="nf"&gt;myFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;3&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Can you guess what will be logged?&lt;br&gt;
Here is our logs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1
Starting Function A
3
Ending Function A
2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You see, our code runs synchronously until we hit the await statement where Promise is yet to be resolved. So when we called &lt;code&gt;myFunction&lt;/code&gt;, our code ran synchronously and logged &lt;code&gt;1&lt;/code&gt; and then it went inside the functionA, here it logged &lt;code&gt;Starting Function A&lt;/code&gt;, and then we hit the await statement where we have to wait for the Promise to resolve, so both of our functions, &lt;code&gt;functionA&lt;/code&gt; and &lt;code&gt;myFunction&lt;/code&gt; runs separately. And our code pointer comes to log &lt;code&gt;3&lt;/code&gt;. And as soon as promise resolves, it logs &lt;code&gt;Ending Function A&lt;/code&gt; and then &lt;code&gt;2&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now it might occur to you why we cannot use &lt;code&gt;async/await&lt;/code&gt; inside forEach.&lt;br&gt;
Let's see the forEach function first:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;forEach&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;callback&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="p"&gt;...&lt;/span&gt;
    &lt;span class="p"&gt;...&lt;/span&gt;
    &lt;span class="nf"&gt;callback&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;...&lt;/span&gt;
    &lt;span class="p"&gt;...&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now when we do:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;myArray&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;forEach&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;async&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;doSomethingWith&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As soon as our code hit await statement, our &lt;code&gt;doSomethingWith&lt;/code&gt; function runs asynchoronously and our code pointer comes back execute the next line in &lt;code&gt;forEach&lt;/code&gt; and hence, it completes the whole forEach and our await statements are still yet to be resolved.&lt;/p&gt;

&lt;p&gt;Let's see an example here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;promiseFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;600&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myArray&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Starting my Function&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nx"&gt;myArray&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;forEach&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Starting forEach with item value&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;promiseFunction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Ending forEach with item value&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;});&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Ending my Function&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="nf"&gt;myFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And here is our logs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Starting my Function
Starting forEach with item value 1
Starting forEach with item value 2
Starting forEach with item value 3
Starting forEach with item value 4
Starting forEach with item value 5
Starting forEach with item value 6
Starting forEach with item value 7
Starting forEach with item value 8
Ending my Function
Ending forEach with item value 1
Ending forEach with item value 2
Ending forEach with item value 3
Ending forEach with item value 4
Ending forEach with item value 5
Ending forEach with item value 6
Ending forEach with item value 7
Ending forEach with item value 8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You see it starts the next callback without ending the previous, that is because each callback is waiting for its await to be resolved. Hence we get to the end of the &lt;code&gt;myFunction&lt;/code&gt; but could not complete callback functions.&lt;/p&gt;

&lt;h3&gt;
  
  
  The workaround:
&lt;/h3&gt;

&lt;p&gt;We can use await Promise.all with map function to have await for each of the callbacks. Here is how:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;promiseFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Starting promiseFunction with item value&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;600&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;});&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Ending promiseFunction with item value&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myArray&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Starting my Function&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nx"&gt;myArray&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;promiseFunction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;
  &lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Ending my Function&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="nf"&gt;myFunction&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;We are simply making the array of Promises by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;myArray&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;promiseFunction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;promiseFunction&lt;/code&gt; returns a function so by &lt;code&gt;map&lt;/code&gt; funtion, we have array of Promises. And we finally resolve all the promises by: &lt;code&gt;await Promise.all&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;And here is our logs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Starting my Function
Starting promiseFunction with item value 1
Starting promiseFunction with item value 2
Starting promiseFunction with item value 3
Starting promiseFunction with item value 4
Starting promiseFunction with item value 5
Starting promiseFunction with item value 6
Starting promiseFunction with item value 7
Starting promiseFunction with item value 8
Ending promiseFunction with item value 1
Ending promiseFunction with item value 2
Ending promiseFunction with item value 3
Ending promiseFunction with item value 4
Ending promiseFunction with item value 5
Ending promiseFunction with item value 6
Ending promiseFunction with item value 7
Ending promiseFunction with item value 8
Ending my Function
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can see, although each &lt;code&gt;promiseFunction&lt;/code&gt; runs asynchronously, but we ensure the our &lt;code&gt;myFunction&lt;/code&gt; ends only when our all the Promises get resolved.&lt;/p&gt;

&lt;p&gt;Hope you learned something today.&lt;br&gt;
Happy Learning ❤️&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Generics in React</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Sun, 10 Dec 2023 18:36:53 +0000</pubDate>
      <link>https://forem.com/husnain/generics-in-react-10p2</link>
      <guid>https://forem.com/husnain/generics-in-react-10p2</guid>
      <description>&lt;h2&gt;
  
  
  What are generics
&lt;/h2&gt;

&lt;p&gt;Have you defined a function/method in any language? If so, you probably know that we are able to define its parameters/arguments that are passed where function is called.&lt;br&gt;&lt;br&gt;
By this we call pass the whatever the value we want to pass to a function and we can decide it at spot.&lt;/p&gt;

&lt;p&gt;But have you ever wondered what if we want to decide the type of some identifier at spot rather than defining it where we created our function. This is where Generics come. Generics are simply the passing of dynamic type to the function (or type/interface) which can be used inside a function.&lt;/p&gt;

&lt;p&gt;It might seem a lot. Let's have it through the example:&lt;/p&gt;

&lt;p&gt;Usually what we do is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;exmapleFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;exmapleFunction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Exmaple Function Called&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;In the above function, we can only pass the data as type of string. But we want data type to be dynamic. Here is what we do to make it dynamic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;exmapleFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="nx"&gt;exmapleFunction&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;Record&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;1&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;This is data&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Now we can pass the dynamic type where we am calling the function, similar to the argument passing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generics in React
&lt;/h2&gt;

&lt;p&gt;Now let's make a component that uses Generics:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;Props&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;MyComponent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Props&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;dataState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setDataState&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;MyComponent&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Example&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/MyComponent&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Now we have passed the dynamic type, generic where we am using the MyComponent.&lt;/p&gt;

&lt;h2&gt;
  
  
  Moving Further
&lt;/h2&gt;

&lt;p&gt;Now we have learned that how we can make and pass the generics to our component. &lt;br&gt;
But what if we want to use generics, but still restrict some type. We want to allow the generics that must satisfy some constraints. We can do it by using the &lt;code&gt;extends&lt;/code&gt; keyword.&lt;br&gt;
Here is how:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt;
    &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;Props&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;MyComponent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Props&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;dataState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setDataState&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;MyComponent&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Example&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/MyComponent&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Now we defined a generic that must extends our &lt;code&gt;ExtendedDataType&lt;/code&gt;, i.e the type we pass must have id as string and value as number in it. Hence the part of the code below shows the error, as string does not satisfy the constraint.&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%2F7ie4hf6tmqip6jrlcb4q.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%2F7ie4hf6tmqip6jrlcb4q.png" alt=" " width="800" height="134"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's pas the correct now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nl"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;Props&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;MyComponent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Props&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;dataState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setDataState&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;AppDataType&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nl"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nl"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;MyComponent&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;AppDataType&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Example&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/MyComponent&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Tada! Now we have correct type that is passed as generic. But notice we didn't change the value of data. That is why we are having this error:&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%2Fktb9y3af74c4naceudce.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%2Fktb9y3af74c4naceudce.png" alt=" " width="800" height="122"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we have to pass the data as type of &lt;code&gt;AppDataType&lt;/code&gt;.&lt;br&gt;
Here it is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nl"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;Props&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;MyComponent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Props&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;dataState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setDataState&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;AppDataType&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nl"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nl"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;appData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;appData&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;app-data-3&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;MyComponent&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;AppDataType&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;appData&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/MyComponent&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have everything as we needed.&lt;br&gt;
But what if we want to have some default value for generics, so if generics is not passed, that default value is considered. We can simply do that by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;MyComponent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;ExtendedDataType&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Props&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;dataState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setDataState&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;props&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now even if we do not pass generics, we will have the &lt;code&gt;T&lt;/code&gt; as &lt;code&gt;ExtendedDataType&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;App&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;MyComponent&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{{&lt;/span&gt;&lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;value-3&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/MyComponent&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;;
&lt;/span&gt;&lt;span class="p"&gt;};&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Note that we have not passed the generics, so T would be ExtendedDataType and so data would be of type ExtendedDataType, and hence we cannot pass data as &lt;code&gt;appData&lt;/code&gt; because appData has one extra feature &lt;code&gt;key&lt;/code&gt;, which ExtendedDataType lacks. &lt;/p&gt;

&lt;p&gt;That's it for today.&lt;br&gt;
Hope it help you learned something.&lt;br&gt;
Happy learning.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>react</category>
      <category>generics</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Apollo GraphQL Implementation in NestJs</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Sat, 21 Oct 2023 18:19:18 +0000</pubDate>
      <link>https://forem.com/husnain/apollo-graphql-implementation-in-nestjs-3chn</link>
      <guid>https://forem.com/husnain/apollo-graphql-implementation-in-nestjs-3chn</guid>
      <description>&lt;p&gt;Today, we will be learning how we can implement the very basics of Apollo GraphQL in NestJs.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is GraphQL and why is GraphQL?
&lt;/h2&gt;

&lt;p&gt;GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data (definition from &lt;a href="https://graphql.org/" rel="noopener noreferrer"&gt;https://graphql.org/&lt;/a&gt;). Before graphQL most web application (still) replies on REST Api as a channel between backend and frontend. &lt;br&gt;
The drawbacks of REST Api are: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Over-fetching or Under-fetching: REST Api always sends back the same data structure for a given url. It could result in over-fetching, i.e getting more data than required by frontend, or under-fetching, i.e getting less data than required by frontend.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Multiple endpoints: Usually REST Api has multiple points, one for each type of data structure.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;GraphQL solves both of these problems by: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Allowing the client, frontend, to fetch the only data that is required. Frontend sends the structure of the data along with the request. And GraphQL only sends back the requested data.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;GraphQL provide single endpoint, usually over /graphql route. Every query or mutation request is sent to this endpoint.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now we have some idea what GraphQL is. Let's start implementing a GraphQL in NestJS.&lt;/p&gt;
&lt;h2&gt;
  
  
  Setting up the project
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;First, we need to have nestjs/cli installed. Here is the command that will install the nestjs/cli: &lt;code&gt;npm i -g @nestjs/cli&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Once, we have installed nestjs cli, we can create a nest project by &lt;code&gt;nest new &amp;lt;project-name&amp;gt;&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Then it will ask you the package manager that you want to use for this project, as shown below: &lt;/p&gt;&lt;/li&gt;
&lt;/ol&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%2F18vmflshabktxnrz3pb1.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%2F18vmflshabktxnrz3pb1.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can select any of them. For this project, I will go with npm. Now it will install some packages and make the directory structure for you. Once done, you would have the following directory structure:&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%2Fwryf0oq9noxjqt2xtan8.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%2Fwryf0oq9noxjqt2xtan8.png" alt=" " width="298" height="402"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our main focus of work would be /src directory. Before moving on, lets understand some basics of the files that you find inside /src directory:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;main.ts&lt;/strong&gt; is the root file and it is where the execution of project begins.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;app.controller.spec.ts&lt;/strong&gt; is the test file. *.spec.ts are used as tests. This would not be covered in this article. So we can delete it. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;app.controller.ts&lt;/strong&gt; is the Controller file. Controllers are one which receives the incoming request, sends the request to Service, and returns the response backed to client. Controllers are the file where we define the api route and method for a specific data. You can read more about Controllers &lt;a href="https://docs.nestjs.com/controllers" rel="noopener noreferrer"&gt;here&lt;/a&gt;. &lt;br&gt;
&lt;strong&gt;But&lt;/strong&gt; we are not going to use Controllers in our GraphQL server as Graphql uses Resolver (described later) rather than Controller.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;app.service.ts&lt;/strong&gt; is the Service. Services are responsible to handle all business logic for a particular data. It is usually responsible to fetch/alter the data from the database.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;app.module.ts&lt;/strong&gt; defines the module. In nestJs, Everything comes under some module. Whole code is sliced down in different modules. It is responsible to configure the structure of the application. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Installing GraphQL
We can have either have &lt;strong&gt;Express&lt;/strong&gt; or &lt;strong&gt;Fastify&lt;/strong&gt; as our web framework. For this tutorial, we would go with Express.
Below is the command to install apollo graphQL:
&lt;code&gt;npm i @nestjs/graphql @nestjs/apollo @apollo/server graphql&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Configuring Apollo GraphQL:
&lt;/h2&gt;

&lt;p&gt;Open /src/app.module.ts and add GraphQL Module in imports like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';

@Module({
  imports: [GraphQLModule.forRoot&amp;lt;ApolloDriverConfig&amp;gt;({
    driver: ApolloDriver,
    autoSchemaFile: true,
  })],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The configuration of GrapqhQL, which is provided as an object in forRoot:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    driver: ApolloDriver,
    autoSchemaFile: true,
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can read more about the configuration &lt;a href="https://docs.nestjs.com/graphql/quick-start#getting-started-with-graphql--typescript" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You might not be in the right directory. If not, move to your project directory by:&lt;br&gt;
&lt;code&gt;cd &amp;lt;project-name&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now you can verify that graphQL server has been configured successfully by running the nest server by the following command: &lt;br&gt;
&lt;code&gt;nest start&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;and open a browser and go to this url:&lt;br&gt;
&lt;code&gt;localhost:3000/graphql&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You would see the grapqQL playground:&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%2Fmvfyv60p6c9doylxmyij.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%2Fmvfyv60p6c9doylxmyij.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Playground is a place where you can test your APIs. We will use playground later in this tutorial when we will be done making some Queries and Mutations in Nest GraphQL Server.&lt;/p&gt;
&lt;h2&gt;
  
  
  Implementing GraphQL
&lt;/h2&gt;

&lt;p&gt;Now its time we start making GraphQL APIs. For that, we need to have some use case. So for this tutorial, we are going to have 2 entities, &lt;strong&gt;Brands&lt;/strong&gt; and their related &lt;strong&gt;Products&lt;/strong&gt;. &lt;/p&gt;
&lt;h3&gt;
  
  
  Brands
&lt;/h3&gt;
&lt;h4&gt;
  
  
  Module
&lt;/h4&gt;

&lt;p&gt;First we are going to implement &lt;strong&gt;Brands&lt;/strong&gt; module.  So to generate a module, you can type the following command in terminal: &lt;br&gt;
&lt;code&gt;nest g module brands&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This command will create a &lt;strong&gt;Brands&lt;/strong&gt; directory inside /src with 'brands.module.ts' file.&lt;/p&gt;
&lt;h4&gt;
  
  
  Model
&lt;/h4&gt;

&lt;p&gt;Now we want &lt;strong&gt;Brands&lt;/strong&gt; model. Which will be a schema for &lt;strong&gt;Brands&lt;/strong&gt;. There are 2 ways to have a schema, Schema First (through Schema Definition Language, SDL) and Code First. Lets pause the tutorial and understand these two first.&lt;/p&gt;
&lt;h5&gt;
  
  
  Difference between Schema First and Code First
&lt;/h5&gt;

&lt;p&gt;These both approaches are used to make a schema. In Schema First, we define the schema, using SDL. &lt;br&gt;
Schema first approach looks 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;type Brands {
  id: Int!
  name: String!
  logo: String
  type: String
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The same thing can be done through Code First by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Field, Int, ObjectType } from '@nestjs/graphql';
@ObjectType()
export class Brands {
  @Field(() =&amp;gt; Int)
  id: number;

  @Field()
  name: string;

  @Field({nullable: true})
  logo?: string;

  @Field({nullable: true})
  type?: string;
}

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

&lt;/div&gt;



&lt;p&gt;Here we are taking help from nestjs/graphql package which provides the required decorators and types.&lt;/p&gt;

&lt;p&gt;Lets go through each thing one by one.&lt;/p&gt;

&lt;h6&gt;
  
  
  @ObjectType() decorator
&lt;/h6&gt;

&lt;p&gt;&lt;strong&gt;@ObjectType()&lt;/strong&gt; is used to define structure of the data. Here we are defining the structure of &lt;strong&gt;Brands&lt;/strong&gt; which will have the above attribute.&lt;/p&gt;

&lt;h6&gt;
  
  
  &lt;a class="mentioned-user" href="https://dev.to/field"&gt;@field&lt;/a&gt;() decorator
&lt;/h6&gt;

&lt;p&gt;&lt;strong&gt;&lt;a class="mentioned-user" href="https://dev.to/field"&gt;@field&lt;/a&gt;()&lt;/strong&gt; is used to define a single attribute of the data. It has multiple over-loaders, one of which is takes a function as first parameter, like in the first field defined above: &lt;br&gt;
&lt;code&gt;@Field(() =&amp;gt; Int)&lt;/code&gt;&lt;br&gt;
Here we are defining type of the id attribute would be Integer. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But why?&lt;/strong&gt; We haven't define the type of other fields in the &lt;a class="mentioned-user" href="https://dev.to/field"&gt;@field&lt;/a&gt; decorator, then why this? Well in TS, type number could be both integer and float. But in GraphQL, an attribute could either be Int or Float. So we have to explicitly tell Nest, that this field is of type Int.&lt;/p&gt;

&lt;p&gt;We do not have to tell Nest explicitly about the string type. That is because string in TS corresponds to String in GraphQL.&lt;/p&gt;

&lt;p&gt;We can also provide an object in the &lt;a class="mentioned-user" href="https://dev.to/field"&gt;@field&lt;/a&gt; decorator as: &lt;br&gt;
&lt;code&gt;@Field({nullable: true, defaultValue: "default"})&lt;/code&gt;&lt;br&gt;
Here you can define multiple things like whether the attribute can be null and what would be default value for that attribute. You can read more about &lt;a class="mentioned-user" href="https://dev.to/field"&gt;@field&lt;/a&gt; decorator &lt;a href="https://docs.nestjs.com/graphql/resolvers#object-types" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h4&gt;
  
  
  Back to Model
&lt;/h4&gt;

&lt;p&gt;Now we need to make a model file in our /src/brands directory named:&lt;br&gt;
&lt;strong&gt;brands.model.ts&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;import { Field, Int, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class Brands {
  @Field((type) =&amp;gt; Int)
  id: number;

  @Field({ nullable: true })
  name?: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For now, we are going with two fields only. Later we will add another field, products, which link each brand to their products.&lt;/p&gt;

&lt;h4&gt;
  
  
  Service
&lt;/h4&gt;

&lt;p&gt;Now we also want &lt;strong&gt;Brands&lt;/strong&gt; service so we can handle all the business logic. To generate a service, here is the command: &lt;br&gt;
&lt;code&gt;nest g service brands&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You would see 'brands.service.ts' in /src. We will alter that file to:&lt;br&gt;
&lt;strong&gt;brands.service.ts&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;import { Injectable } from '@nestjs/common';
import { Brands } from './brands.model';

@Injectable()
export class BrandsService {
  private readonly brands: Brands[] = [
    { id: 1, name: 'Adidas' },
    { id: 2, name: 'Nike' },
  ];
  findById(id: number): Brands {
    return this.brands.find((brand) =&amp;gt; brand.id == id);
  }
  findAll(): Brands[] {
    return this.brands;
  }
  addBrand(id: number, name: string): Brands {
    this.brands.push({ id, name });
    return { id, name };
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  @Injectable() decorator
&lt;/h5&gt;

&lt;p&gt;@Injectable() is used to let Nest know that the class we are defining is injectable to other providers and controllers. By this, we can access the class instance through other classes. &lt;/p&gt;

&lt;p&gt;In Brands class, we have defined a variable brands. Usually this is to be done through database. Database is responsible for storing such data. But as we are not going to use any database in this tutorial, we are storing the data within the app. &lt;/p&gt;

&lt;p&gt;Furthermore, we have defined some function so fetch from and add to brands array.&lt;/p&gt;

&lt;h4&gt;
  
  
  Resolver
&lt;/h4&gt;

&lt;p&gt;Rather than using Controller, which defines the API, we use Resolver in GraphQL. So make a file in /src/brands:&lt;br&gt;
&lt;strong&gt;brands.resolver.ts&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;import {
  Args,
  Int,
  Mutation,
  Query,
  Resolver,
} from '@nestjs/graphql';
import { Brands } from './brands.model';
import { BrandsService } from './brands.service';

@Resolver(() =&amp;gt; Brands)
export class BrandsResolver {
  constructor(
    private brandsService: BrandsService,
  ) {}

  @Query(() =&amp;gt; [Brands])
  getAllBrands(): Brands[] {
    return this.brandsService.findAll();
  }

  @Query(() =&amp;gt; Brands)
  getBrandById(@Args('id', { type: () =&amp;gt; Int }) id: number): Brands {
    return this.brandsService.findById(id);
  }

  @Mutation(() =&amp;gt; Brands)
  addBrand(
    @Args('id', { type: () =&amp;gt; Int }) id: number,
    @Args('name') name: string,
  ): Brands {
    return this.brandsService.addBrand(id, name);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  @Resolver() decorator
&lt;/h5&gt;

&lt;p&gt;@Resolver decorator is used to define a resolver, a class which defines GraphQL Queries and Mutations, which client can use for requests. In @Resolver, we need to pass a function as the first parameter which returns the Object that this Resolver would resolve, in our case, it's Brands. &lt;br&gt;
&lt;code&gt;@Resolver(() =&amp;gt; Brands)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In the class BrandsResolver, we defined a constructor. Although we are not doing anything inside the block of constructor, but we are defining the BrandsService as brandsService by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;constructor(
    private brandsService: BrandsService,
  ) {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are injecting our BrandsService that we made before with @Injectable()&lt;/p&gt;

&lt;p&gt;Next we are defining a GraphQL Query by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Query(() =&amp;gt; [Brands])
  getAllBrands(): Brands[] {
    return this.brandsService.findAll();
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  @Query() decorator
&lt;/h5&gt;

&lt;p&gt;@Query is like the GET Api of REST, it takes first parameter as function which returns the &lt;strong&gt;type&lt;/strong&gt; of the &lt;strong&gt;return type of request&lt;/strong&gt;. In the above Query, we are returning Brands array back to the client when client calls this API.&lt;br&gt;
Below it, we define a function, in which we fetch the Brands by using the BrandsService. Name of the function will be used as name of the Query.&lt;/p&gt;

&lt;p&gt;After the queries, we are defining a mutation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Mutation(() =&amp;gt; Brands)
  addBrand(
    @Args('id', { type: () =&amp;gt; Int }) id: number,
    @Args('name') name: string,
  ): Brands {
    return this.brandsService.addBrand(id, name);
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  @Mutation() decorator
&lt;/h5&gt;

&lt;p&gt;@Mutation is like the POST API of REST. It takes the first parameter as function, same as Query.&lt;br&gt;
Below it, we define a function which can have any number of arguments. These variables are similar to body data in REST API. But we need to define these arguments through @Args decorator.&lt;/p&gt;
&lt;h5&gt;
  
  
  @Args() decorator
&lt;/h5&gt;

&lt;p&gt;@Args is similar to &lt;a class="mentioned-user" href="https://dev.to/field"&gt;@field&lt;/a&gt; decorator that we learned earlier, except it takes first argument as name of argument and second as object which can define &lt;strong&gt;type&lt;/strong&gt; and other things. &lt;/p&gt;

&lt;p&gt;Lastly, inside the function, we call the service class function to add brand by passing the arguments we got through @Args.&lt;/p&gt;

&lt;p&gt;We are almost done with Brands. Just a single step remaining, we need to all the Services and Resolver in the &lt;strong&gt;Brands&lt;/strong&gt; module by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { BrandsService } from './brands.service';
import { BrandsResolver } from './brands.resolver';

@Module({
  providers: [BrandsService, BrandsResolver],
})
export class BrandsModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Brands API Testing
&lt;/h5&gt;

&lt;p&gt;Now we have our &lt;strong&gt;Brands&lt;/strong&gt; done. Let's test Brands API in playground. Open browser and go to &lt;code&gt;http://localhost:3000/graphql&lt;/code&gt;&lt;br&gt;
We can now see the &lt;strong&gt;Docs&lt;/strong&gt; and &lt;strong&gt;Schema&lt;/strong&gt; on the right side of playground.&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%2F1jugerrajd1bqigkms8n.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%2F1jugerrajd1bqigkms8n.png" alt=" " width="406" height="870"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And we can test any API, like:&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%2Fxfpp7vyumst7q02ix5zl.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%2Fxfpp7vyumst7q02ix5zl.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Products
&lt;/h3&gt;

&lt;p&gt;Now lets quickly create Products Module to handle Products entity.&lt;/p&gt;
&lt;h4&gt;
  
  
  Module
&lt;/h4&gt;

&lt;p&gt;Generate module by&lt;br&gt;
&lt;code&gt;nest g module products&lt;/code&gt;&lt;/p&gt;
&lt;h4&gt;
  
  
  Model
&lt;/h4&gt;

&lt;p&gt;Create a file inside /src/products:&lt;br&gt;
&lt;strong&gt;products.model.ts&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;import { Field, Int, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class Products {
  @Field((type) =&amp;gt; Int)
  id: number;

  @Field({ nullable: true })
  name?: string;

  @Field((type) =&amp;gt; Int)
  brandId: number;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We needed to add brandId as well to link the Brands with their Products, we are using one-many relationship here.&lt;/p&gt;

&lt;h4&gt;
  
  
  Service
&lt;/h4&gt;

&lt;p&gt;Generate service by &lt;code&gt;nest g service products&lt;/code&gt;.&lt;br&gt;
&lt;strong&gt;products.service.ts&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;import { Injectable } from '@nestjs/common';
import { Products } from './products.model';

@Injectable()
export class ProductsService {
  private readonly products: Products[] = [
    {
      id: 1,
      name: 'Product A',
      brandId: 1,
    },
    {
      id: 2,
      name: 'Product B',
      brandId: 1,
    },
    {
      id: 3,
      name: 'Product C',
      brandId: 2,
    },
  ];

  findById(id: number): Products {
    return this.products.find((product) =&amp;gt; product.id == id);
  }

  findByBrandId(brandId: number): Products[] {
    return this.products.filter((product) =&amp;gt; product.brandId == brandId);
  }

  addProduct(id: number, name: string, brandId: number): boolean {
    this.products.push({ id, name, brandId });
    return true;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Resolver
&lt;/h4&gt;

&lt;p&gt;Make a file in /src/products:&lt;br&gt;
&lt;strong&gt;products.resolver.ts&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;import { Args, Int, Mutation, Query, Resolver } from '@nestjs/graphql';
import { Products } from './products.model';
import { ProductsService } from './products.service';

@Resolver(() =&amp;gt; Products)
export class ProductsResolver {
  constructor(private productsService: ProductsService) {}
  @Query((returns) =&amp;gt; [Products])
  getProductsByBrandId(
    @Args('brandId', { type: () =&amp;gt; Int }) brandId: number,
  ): Products[] {
    return this.productsService.findByBrandId(brandId);
  }
  @Query((returns) =&amp;gt; Products)
  getProductById(@Args('id', { type: () =&amp;gt; Int }) id: number): Products {
    return this.productsService.findById(id);
  }
  @Mutation((returns) =&amp;gt; Boolean)
  addProduct(
    @Args('id', { type: () =&amp;gt; Int }) id: number,
    @Args('name') name: string,
    @Args('brandId', { type: () =&amp;gt; Int }) brandId: number,
  ): boolean {
    return this.productsService.addProduct(id, name, brandId);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Modify the&lt;br&gt;
&lt;strong&gt;products.module.ts&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;import { Module } from '@nestjs/common';
import { ProductsService } from './products.service';
import { ProductsResolver } from './products.resolver';

@Module({
  providers: [ProductsService, ProductsResolver],
})
export class ProductsModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Linking Products to Brands
&lt;/h3&gt;

&lt;p&gt;Here we need to modify some of the files of Brands Module. First of all, we need to pass ProductsService in providers of Brands so that we can use ProductsService to find the Products related to a Brand by using &lt;code&gt;findByBrandId&lt;/code&gt; function that we defined in ProductsService class above.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;brands.module.ts&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;import { Module } from '@nestjs/common';
import { BrandsService } from './brands.service';
import { BrandsResolver } from './brands.resolver';
import { ProductsService } from 'src/products/products.service';

@Module({
  providers: [BrandsService, BrandsResolver, ProductsService],
})
export class BrandsModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We also need to add a field in Brands Model as &lt;strong&gt;products&lt;/strong&gt; which will corresponds to Brands products&lt;br&gt;
&lt;strong&gt;brands.model.ts&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;import { Field, Int, ObjectType } from '@nestjs/graphql';
import { Products } from 'src/products/products.model';

@ObjectType()
export class Brands {
  @Field((type) =&amp;gt; Int)
  id: number;

  @Field({ nullable: true })
  name?: string;

  @Field((type) =&amp;gt; [Products], { defaultValue: [] })
  products?: Products[];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly, we need to Resolve this newly added field in Brands Resolver,&lt;br&gt;
&lt;strong&gt;brands.resolver.ts&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;import {
  Args,
  Int,
  Mutation,
  Parent,
  Query,
  ResolveField,
  Resolver,
} from '@nestjs/graphql';
import { Brands } from './brands.model';
import { BrandsService } from './brands.service';
import { Products } from 'src/products/products.model';
import { ProductsService } from 'src/products/products.service';

@Resolver(() =&amp;gt; Brands)
export class BrandsResolver {
  constructor(
    private brandsService: BrandsService,
    private productsService: ProductsService,
  ) {}

  @ResolveField()
  products(@Parent() brand: Brands): Products[] {
    const brandId = brand.id;
    return this.productsService.findByBrandId(brandId);
  }

  @Query((returns) =&amp;gt; [Brands])
  getAllBrands(): Brands[] {
    return this.brandsService.findAll();
  }

  @Query((returns) =&amp;gt; Brands)
  getBrandById(@Args('id', { type: () =&amp;gt; Int }) id: number): Brands {
    return this.brandsService.findById(id);
  }

  @Mutation((returns) =&amp;gt; Brands)
  addBrand(
    @Args('id', { type: () =&amp;gt; Int }) id: number,
    @Args('name') name: string,
  ): Brands {
    return this.brandsService.addBrand(id, name);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  @ResolveField() decorator
&lt;/h5&gt;

&lt;p&gt;We have added a @ResolveField decorator in the resolver file. When we have an object, &lt;strong&gt;Object A&lt;/strong&gt;, as a field of other object, Object B, like Products as a field for Brands, we need to resolve that field, that is to define a way through which &lt;strong&gt;Object A&lt;/strong&gt; is fetched on some link attribute. Here linking attribute is Brand ID. Brand ID is &lt;strong&gt;id&lt;/strong&gt; in &lt;strong&gt;brands.model.ts&lt;/strong&gt; and &lt;strong&gt;brandId&lt;/strong&gt; in &lt;strong&gt;products.model.ts&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In the function provided after decorator, requires first argument as parent object, i.e Brands here. And we define it using @Parent decorator like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
...
@ResolveField()
  products(@Parent() brand: Brands)
...
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can access Brands Id by brand.id and pass it to the ProductsService findByBrandId function.&lt;/p&gt;

&lt;p&gt;That's it. Save everything and re run the server by:&lt;br&gt;
&lt;code&gt;nest start&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Go to playground and verify that we can access Products of each Brands:&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%2Fmhiffwn0g690oefegd3a.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%2Fmhiffwn0g690oefegd3a.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;That's a wrap. Hope you found this article helpful.&lt;br&gt;
You can access the repo &lt;a href="https://github.com/kito-arch/NestJs-Apollo" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
Keep learning ❤️&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>graphql</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Testing in React</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Thu, 21 Sep 2023 19:26:25 +0000</pubDate>
      <link>https://forem.com/husnain/testing-in-react-42cm</link>
      <guid>https://forem.com/husnain/testing-in-react-42cm</guid>
      <description>&lt;p&gt;In today's world, almost every product, regardless whether it is software or not, is released when the required tests are done over it. Tests assure that the product is up to the mark. &lt;/p&gt;

&lt;p&gt;Let's get started with testing your React application. Recently I made a post of developing a basic todo app in React typescript, you can find that &lt;a href="https://dev.to/husnain/lets-make-your-first-react-typescript-todo-web-app-3e8c"&gt;here&lt;/a&gt;. &lt;br&gt;
For Reference, this is how it looks like: &lt;br&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%2Fruipw0jndo2sbggul647.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%2Fruipw0jndo2sbggul647.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We will be writing some tests on this todo app to understand the very basics of React testing.&lt;/p&gt;
&lt;h2&gt;
  
  
  Installing Libraries
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Jest, a library for testing purposes, primarily for React. &lt;br&gt;
&lt;code&gt;npm install --save-dev jest&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Jest Types, typeScript type definitions for Jest.&lt;br&gt;
&lt;code&gt;npm install --save-dev @types/jest&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;ts-jest, a TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in TypeScript (as our project is in Typescript)&lt;br&gt;
&lt;code&gt;npm install --save-dev ts-jest&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;React Testing Library, a library which provides us to grab the specific components of the web page (in React) and pass it to testing library such as Jest. &lt;br&gt;
&lt;code&gt;npm install --save-dev @testing-library/react&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Configuration
&lt;/h2&gt;

&lt;p&gt;We need to configure jest.config.mjs You might not find it in your files at first. So you need to run the following command: &lt;br&gt;
&lt;code&gt;npx jest --init&lt;/code&gt;&lt;br&gt;
This will ask some questions. You can answer it if you want to customize it according to you but below is a reference picture if you are totally new to it:&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%2Fb9mqcfopnomo4en6j1j4.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%2Fb9mqcfopnomo4en6j1j4.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now you would need to open jest.config.mjs and add the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
...
const config = {
...
     preset: "ts-jest",
...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Extension
&lt;/h2&gt;

&lt;p&gt;It would be really helpful if we download this extension in VSCode, &lt;code&gt;Jest Runner&lt;/code&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%2Fbqm80f954y2hortdqs6w.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%2Fbqm80f954y2hortdqs6w.png" alt=" " width="358" height="123"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This helps run the tests through the GUI rather than writing the path of file by ourselves in the CLI.&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%2Flv3up5qua33wid9wwwhn.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%2Flv3up5qua33wid9wwwhn.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What we are going to test
&lt;/h2&gt;

&lt;p&gt;There could be many things to test, but in this tutorial we will be covering the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;UI Rendering, i.e whether the component is being rendered or not.&lt;/li&gt;
&lt;li&gt;State changing, i.e when I click on 'Done' button, does the card moves from 'Todo' state to 'Done' state.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Testing UI Rendering
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Make a file in /src, named as 'App.test.tsx'. This would be the file where we will be writing our tests. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Testing:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { render, screen } from "@testing-library/react";
import { TodoPage } from "./pages/todo";
import { DummyTodoList } from "./dummydata";

describe("Todos", () =&amp;gt; {
  it("should render all the data", () =&amp;gt; {
    render(&amp;lt;TodoPage /&amp;gt;);
    const { getByText } = screen;
    DummyTodoList.forEach((item) =&amp;gt; {
      expect(getByText(item.title)).toBeTruthy();
    });
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Explanation:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;describe&lt;/strong&gt; (provided by jest) is used to describe a test suite, group of related tests. It takes 2 args, first, a string, which describes what test suite is related to. Second, a function, which will have different tests.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;it&lt;/strong&gt; (provided by jest) is used to describe an individual test. It is written inside the function provided as second parameter to &lt;strong&gt;describe&lt;/strong&gt;. &lt;strong&gt;it&lt;/strong&gt; also takes 2 parameters, a string, describing the exact test. Second, a function which would actually contain the logic of testing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;render&lt;/strong&gt; is a function of react testing library, which renders the component. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;screen&lt;/strong&gt; is an object provided by the react testing library that provides multiple functions, like &lt;strong&gt;getByText&lt;/strong&gt;, to access the element in the DOM&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;expect&lt;/strong&gt; (provided by jest) is a function which takes an one argument, which we need to test, like the element we are passing, and returns an object which provides multiple functions like toBeTruthy(), meaning it is found in the DOM.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Result&lt;/li&gt;
&lt;/ol&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%2Ff0wdozjzzbrri9urf7bz.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%2Ff0wdozjzzbrri9urf7bz.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Examples of &lt;strong&gt;expect&lt;/strong&gt; for understanding:&lt;br&gt;
&lt;code&gt;expect(3).toBe(3) - test pass&lt;/code&gt;&lt;br&gt;
&lt;code&gt;expect(&amp;lt;any function&amp;gt;).toBeCalled() - test whether the given function is called&lt;/code&gt;&lt;br&gt;
&lt;code&gt;expect(&amp;lt;any function&amp;gt;).toBeCalledTimes(2) - test whether the given function is called 2 times&lt;/code&gt;&lt;br&gt;
&lt;code&gt;expect(3).not.toBeGreaterThan(1) - test fails as 3 is greater than 1, note that there is **not**&lt;/code&gt;&lt;br&gt;
&lt;code&gt;expect(false).toBeTruthy() - test fails as false is not true&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Testing todos in respective tabs
&lt;/h3&gt;

&lt;p&gt;Now we want to test that our dummy data is in the respective tabs, i.e we want to check that the todo which is &lt;strong&gt;unchecked&lt;/strong&gt; must be in the Todo tab and &lt;strong&gt;checked&lt;/strong&gt; todos must be in Done tab.&lt;br&gt;
One way of doing that is, we verify that the text is crossed, i.e style.textDecoration is 'none' in &lt;strong&gt;unchecked&lt;/strong&gt; and style.textDecoration is 'line-through' in &lt;strong&gt;checked&lt;/strong&gt;.&lt;br&gt;
We can do it by (inside the function provided as second parameter of describe):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it("should render all the data in the respective tabs", () =&amp;gt; {
    render(&amp;lt;TodoPage /&amp;gt;);
    const { getByText } = screen;
    const uncheckedItems = DummyTodoList.filter((item) =&amp;gt; !item.checked);
    const checkedItems = DummyTodoList.filter((item) =&amp;gt; item.checked);
    uncheckedItems.forEach((item) =&amp;gt; {
      expect(getByText(item.title).style.textDecoration).toBe("none");
    });
    checkedItems.forEach((item) =&amp;gt; {
      expect(getByText(item.title).style.textDecoration).toBe("line-through");
    });
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result&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%2F5wcw7dw76wy42mfralec.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%2F5wcw7dw76wy42mfralec.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Testing whether clicking on checkbox makes our todo checked/unchecked
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it("should move unchecked todo to Done tab when click on checkbox", () =&amp;gt; {
    render(&amp;lt;TodoPage /&amp;gt;);
    const { getByText, getAllByRole } = screen;
    expect(getByText(DummyTodoList[0].title).style.textDecoration).toBe("none");

    const firstCheckBox = getAllByRole("checkbox")[0];
    fireEvent.click(firstCheckBox);
    expect(getByText(DummyTodoList[0].title).style.textDecoration).toBe(
      "line-through"
    );
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that we have used, getAllByRole, also provided by screen, fetches all the element having a specified role. Checkbox has role of &lt;strong&gt;checkbox&lt;/strong&gt;. You can read more about the different roles of different elements &lt;a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then with all the elements, we selected the very first element by using [0]. This gives us the first checkbox in the DOM. We confirmed that the todo is not checked and is under Todo Tab by simply checking the styles.textDecoration as 'none'.&lt;/p&gt;

&lt;p&gt;Then we clicked on the checkbox we first fetched, by using fireEvent (also provided by React Testing Library). And then we verified that todo is &lt;strong&gt;checked&lt;/strong&gt; by, again, checking style.textDecoration as 'line-through'&lt;/p&gt;

&lt;p&gt;Result:&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%2F0s06n7uzzv5pgc0y2ekt.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%2F0s06n7uzzv5pgc0y2ekt.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Github Repo
&lt;/h2&gt;

&lt;p&gt;Tests are pushed to this &lt;a href="https://github.com/kito-arch/React-Typescript-Todo-App" rel="noopener noreferrer"&gt;repo&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Hope this article helped you understand the very basics of testing. Keep learning ❤️&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>testing</category>
      <category>react</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Git Basic Commands</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Sun, 20 Aug 2023 13:37:23 +0000</pubDate>
      <link>https://forem.com/husnain/git-basic-commands-47nl</link>
      <guid>https://forem.com/husnain/git-basic-commands-47nl</guid>
      <description>&lt;p&gt;Today, we will be learning about the Git Commands which are required when starting to work as a team. We will start from basics.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Git
&lt;/h2&gt;

&lt;p&gt;First of all, let me tell you what is Git and why we need it as a software engineer. &lt;br&gt;
If you have been doing some software developing, you might have faced a situation where you need to keep multiple backups of your project, each backup having some is newer version of previous, like, Backup_v1, Backup_v2. I used to do the very same when I started learning coding. But this kind of work is really unorganized and annoying. Then comes git, a tool which keep track of your code history so if at any time you wanna go back to previous versions, you can, with a single command. Other than keeping track of code, git is really useful when working on the project as a team.&lt;/p&gt;

&lt;p&gt;Now, its our time to learn some git commands, and we will do it by going through a story. This will make it easy to understand.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Story
&lt;/h2&gt;

&lt;p&gt;Let's say Bob is a fresh Software Engineer who is hired by the company The Softee. The Softee is working on the project called Project X. Bob is given the access of the repository of Project X. Now Bob will have to download all the code of the Project X. So how will he do it?&lt;/p&gt;




&lt;h3&gt;
  
  
  Git Clone Command
&lt;/h3&gt;

&lt;p&gt;Bob will download the repository by copying the repo and clone it in the terminal.&lt;br&gt;
&lt;code&gt;git clone &amp;lt;repo_link&amp;gt;&lt;/code&gt;&lt;br&gt;
This will download all the code of the main branch to his PC.&lt;/p&gt;




&lt;p&gt;Back to story, Now Bob got all the code. Bob has been given a task, Bug Task, to remove a small bug. So rather than starting working on the task, first Bob need to make a separate branch. But why? This is because if Bob does not code well, i.e, not having good quality code, or introducing another bug, or anything else that is not required, it will not affect the main branch. Separate branch keeps the Bob's code separate, and when everything is done by Bob's side, his code will be reviewed by the team and if  everything is fine, then Bob's code will be merged to main branch. So to make a branch:&lt;/p&gt;




&lt;h3&gt;
  
  
  Making Branch in git
&lt;/h3&gt;

&lt;p&gt;Bob will make a branch by:&lt;br&gt;
&lt;code&gt;git branch bugtask&lt;/code&gt;&lt;br&gt;
This will make a branch but Bob is still on main branch, so to enter his newly made branch, he can use:&lt;br&gt;
&lt;code&gt;git checkout bugtask&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;To make a branch and enter in a single line, following command is used:&lt;br&gt;
&lt;code&gt;git checkout -b bugtask&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;He can also verify on which branch he is by:&lt;br&gt;
&lt;code&gt;git branch&lt;/code&gt;&lt;br&gt;
It will list all the branched, and asterik,  *bugtask, means he is on bugtask branch.&lt;/p&gt;




&lt;p&gt;Now Bob is in his branch where he can start working on the bug. When he is done with removing bug, he will need to commit the branch. Committing in git means making a tracking points, i.e a version of backup. And it is necessary to commit before pushing the code. Pushing code means storing code on the remote repository, meaning it will be saved online on github. So even if code gets deleted from your PC, code will be available online. So Bob can make a commit by:&lt;/p&gt;




&lt;h3&gt;
  
  
  Committing changes in git
&lt;/h3&gt;

&lt;p&gt;Before committing, Bob need to stage the files he want to commit, i.e he need to tell git that these are the files which are needed to be saved as a backup. So most of the times we need to save all the files, so we stage all files by:&lt;br&gt;
&lt;code&gt;git add .&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If there is some specific file, we can:&lt;br&gt;
&lt;code&gt;git add &amp;lt;filename&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;After staging files, he need to commit by:&lt;br&gt;
&lt;code&gt;git commit -m '&amp;lt;commit message&amp;gt;'&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Commit message is a brief description about the commit. This could be whatever you want but its better to have some meaningful description so that at later, anyone can see what was done in this commit. Mostly we use &lt;a href="https://www.conventionalcommits.org/en/v1.0.0/" rel="noopener noreferrer"&gt;Conventional Commits&lt;/a&gt;, a standard way to write a message of commit.  &lt;/p&gt;




&lt;p&gt;Now committing is done. Bob need to push the code, i.e send the code to remote repo so it gets saved online and everyone in the team can see it. So he can push by:&lt;/p&gt;




&lt;h3&gt;
  
  
  Pushing Code
&lt;/h3&gt;

&lt;p&gt;He can push the code by:&lt;br&gt;
&lt;code&gt;git push -u &amp;lt;repo_name&amp;gt; &amp;lt;remote_branch_name&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;-u is optional, it sets the upstream for the branch, i.e if you use -u, then it will link your local branch to your remote branch. So later you would not need to write the whole above command, rather just use:&lt;br&gt;
&lt;code&gt;git push&lt;/code&gt;&lt;br&gt;
and git will understand that you are pushing your branch, bugtask to your repo. Git push will push the branch on which you are currently on.&lt;/p&gt;




&lt;p&gt;Now code is pushed, and team can easily review Bob's code and if it is up to the mark, team will merge Bob's code to main branch, i.e add Bob's code to main branch.&lt;/p&gt;

&lt;p&gt;Let's say Bob's pair programmer, Alex, also working on the same branch, bugtask, and he pushed some code too. So Bob can get the latest changes to the branch by:&lt;/p&gt;




&lt;h3&gt;
  
  
  Pulling Changes
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;git pull --set-upstream &amp;lt;remote_repo&amp;gt; &amp;lt;remote_branch_name&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;--set-upstream is same as -u when pushing the code.&lt;br&gt;
Both of these commands link your local branch to remote branch. So if you typed once -u or --set-upstream, it will link and then you can pull by simply: &lt;br&gt;
&lt;code&gt;git pull&lt;/code&gt;&lt;br&gt;
and push by:&lt;br&gt;
&lt;code&gt;git push&lt;/code&gt;&lt;br&gt;
while being in required branch, i.e, bugtask.&lt;/p&gt;




&lt;p&gt;Now let's suppose another scenario where Bob is half-way between solving the bug that was assigned to him. Now he want to see the code of another branch, let's say branch-x, where he can get some help on how to remove a bug. Now Bob need to save the whatever half changes he did for removing the bug. So he can stash the changes, Stashing means saving the changes in the local PC so one can get those changes later. So Bob can stash his changes by: &lt;/p&gt;




&lt;h3&gt;
  
  
  Stashing Changes
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;git stash .&lt;/code&gt;&lt;br&gt;
to stash all files that are changed.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;git stash &amp;lt;filename&amp;gt;&lt;/code&gt;&lt;br&gt;
to stash any specific file.&lt;/p&gt;




&lt;p&gt;Now Bob can move around any branch and see all code he want to help him out by:&lt;/p&gt;




&lt;h3&gt;
  
  
  Changing Branch
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;git branch &amp;lt;branch_name&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In this case, as Bob want to see branch branch-x:&lt;br&gt;
&lt;code&gt;git branch branch-x&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;When he got the help, he can switch back to his branch by:&lt;br&gt;
&lt;code&gt;git branch bugtask&lt;/code&gt;&lt;/p&gt;




&lt;p&gt;But now he wont have those changes that he did to remove bug. These changes are in stash so he can get back all the stashed changes by:&lt;/p&gt;




&lt;h3&gt;
  
  
  Getting Changed back from stash
&lt;/h3&gt;

&lt;p&gt;He can get back the stashed changes by:&lt;br&gt;
&lt;code&gt;git stash pop&lt;/code&gt;&lt;br&gt;
and all the changes he stashed in the most recent stash will be recovered in working directory.&lt;/p&gt;




&lt;p&gt;I guess that is enough for this post. Soon we will be learning some advanced git commands which are really useful in the life of software engineer.&lt;/p&gt;

&lt;p&gt;Hope it helped you out.&lt;br&gt;
Feel free to ask anything.&lt;/p&gt;

</description>
      <category>git</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Improve performance of React Application</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Sat, 05 Aug 2023 15:58:29 +0000</pubDate>
      <link>https://forem.com/husnain/improve-performance-of-react-application-3i71</link>
      <guid>https://forem.com/husnain/improve-performance-of-react-application-3i71</guid>
      <description>&lt;p&gt;Performance is the major issue when we develop a medium to large scale projects. React provide us various ways through which we can improve the performance of our react app. Most of it are the hooks that are provided by react, but performance issue is not limited to that. Most of the performance issues in React is because of the re-rendering of the components. So let's discuss about it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Re-rendering in React:
&lt;/h2&gt;

&lt;p&gt;If you know react, you would know that whenever the props or states gets changed, component re-renders. And not only re-renders it self but all the children also gets re-rendered all the way to the leaf node, i.e last child in the DOM tree, when the parent gets re-rendered. &lt;br&gt;
Furthermore, when component re-renders, it not only affects the DOM, but also re-declare/re-define every variable and function which is the part of the component. This further effects the performance.&lt;/p&gt;
&lt;h2&gt;
  
  
  Minimizing the re-rendering ripple effect:
&lt;/h2&gt;
&lt;h3&gt;
  
  
  Preventing child component to re-render whenever parent re-render:
&lt;/h3&gt;

&lt;p&gt;We can prevent the child component re-rendering on parent re-rendering by use React.memo. By using React.memo, our child component only gets re-rendered only if its props gets changed. So even if our parent is getting re-render, regardless what the reason is, if the props passed to children are not changed, then child component will not re-render.&lt;br&gt;
Here is the 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 ChildComponent = ({arg1, arg2}) =&amp;gt; {
...
...
}

export default React.memo(ChildComponent)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Preventing the re-defining of the functions on re-render:
&lt;/h3&gt;

&lt;p&gt;Almost all of our functions in the component does not need to be re-defined on the re-render, or we only need to redefine those only if some specific states gets changed. So we can prevent functions to be re-defined on every re-render by using useCallback hook. This hook stores the function and only re-define it if any variable provided in the dependency array gets changed. So we need to provide every variable in the dependency array that is not a part of function but used in function, like:&lt;br&gt;
&lt;/p&gt;

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

const Component = ({arg1, arg2}) =&amp;gt; {

     const [myState, setMyState] = useState(0)
     const doSomething = useCallback(()=&amp;gt;{
          &amp;lt;do something with myState&amp;gt;
     }, [myState])
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, notice I have added myState in the dependency array. This is because, if I do not add myState in dependency array, doSomething will store the value of myState and always use that value. So even of myState value update to 3, doSomethinig will still be using 0 as myState. So to update our function with new value of myState, we need to add myState in dependency array.&lt;/p&gt;

&lt;h3&gt;
  
  
  Preventing the re-defining of the variable on re-render:
&lt;/h3&gt;

&lt;p&gt;Some of the variables in the component needs to a very complex function, and then store the value returned by that function. So if we do not prevent this calling of a complex function, we can lose performance. To prevent this, we can use useMemo hook to store the value and provide those variables in the dependency array over which, when any of those variable gets updated, this complex function calculates and return the value again.&lt;br&gt;
&lt;/p&gt;

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

const Component = ({arg1, arg2}) =&amp;gt; {

     const [myState, setMyState] = useState(0)
     const someValue = useMemo(() =&amp;gt; complexFunction(myState), [myState])
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Preventing re-rendering when map function is used:
&lt;/h3&gt;

&lt;p&gt;Have you noticed that whenever you use map, without use the prop 'key', it gives you warning. Key prop is useful for performance because React identifies and keep track of the components in the virtual DOM through the key prop. But when using map function, react does not automatically assign key to the components' array that is returned by map function. So if any only one component inside the map function changes, its will re-render all the components that are provided by the map function. So to avoid this re-rendering and restricting it to only re-render the component which got changed, we need to assign the key.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
...
todoArr.map((el)=&amp;gt;{
     return(
          &amp;lt;TodoComponent key = {el.id} title = {el.title}/&amp;gt;
     )
})
...
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Preventing re-rendering of input:
&lt;/h3&gt;

&lt;p&gt;Most of the beginners in React, including myself when I started learning React, use controlled inputs through state. Something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
const [myInput, setMyInput] = useState(0)
...
...
&amp;lt;input value = {myInput} onChange = {(event)=&amp;gt;{setMyInput(event.target.value)}}
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This causes re-rendering of input whenever we type a single character. &lt;br&gt;
So unless you need to make your input controlled, for any reason like validation of input, you should use uncontrolled input. Which you can do using useRef hook as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
const myInputRef = useRef()
...
...
&amp;lt;input ref = {myInputRef}/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and get the value of input by:&lt;br&gt;
&lt;code&gt;myInputRef.current.value&lt;/code&gt;&lt;/p&gt;




&lt;p&gt;These are some of the ways you can improve performance of your react application. There are many other factors which affect the performance which I might have skipped.&lt;/p&gt;

&lt;p&gt;Hope this article helped you.&lt;/p&gt;

</description>
      <category>react</category>
      <category>performance</category>
      <category>javascript</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Let's make your first React Typescript Todo web app</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Mon, 17 Jul 2023 11:16:00 +0000</pubDate>
      <link>https://forem.com/husnain/lets-make-your-first-react-typescript-todo-web-app-3e8c</link>
      <guid>https://forem.com/husnain/lets-make-your-first-react-typescript-todo-web-app-3e8c</guid>
      <description>&lt;p&gt;When I started React with typescript, I found it a bit difficult to code as I had little to no experience in typescript. So I had to go through the web and understand the basics. &lt;/p&gt;

&lt;p&gt;Typescript is not that hard as it looks like, it's just a superset of Javascript. So if you know Javascript, it would be really easy to understand.&lt;/p&gt;

&lt;p&gt;So let's get started.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating React App through Vite
&lt;/h2&gt;

&lt;p&gt;At first, most react developers, including myself, used to create the project through Create-React-App. But this package got deprecated and it is no further updated.&lt;/p&gt;

&lt;p&gt;So I shifted to Vite, which is pretty good and much faster.&lt;/p&gt;

&lt;p&gt;Before creating React App, you must have Vite installed. You can install Vite by the following command in the terminal:&lt;br&gt;
&lt;code&gt;npm i -g vite&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;To create a React App:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Open Terminal&lt;/li&gt;
&lt;li&gt;Type: &lt;code&gt;npm create vite@latest app-name&lt;/code&gt;, app-name is the name of the app, in our case, it is 'todo'. So command becomes &lt;code&gt;npm create vite@latest todo&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Now it will ask which template we want to use, select 'React' with arrow keys and press enter&lt;/li&gt;
&lt;li&gt;Now it will ask for the language, select 'Typescript'&lt;/li&gt;
&lt;li&gt;It will create a folder named 'todo'. &lt;/li&gt;
&lt;li&gt;Move to folder by &lt;code&gt;cd todo&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Install the required packages by &lt;code&gt;npm install&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;You can run the basic Vite project by &lt;code&gt;npm run dev&lt;/code&gt;
and open the browser and type in search bar: &lt;code&gt;localhost:5173&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Installing Frontend Libraries
&lt;/h2&gt;

&lt;p&gt;We will be using MUI for this project as it provides variety of components and we do not need to make components from the scratch. So type the following in the terminal:&lt;br&gt;
&lt;code&gt;npm install @mui/material @emotion/react @emotion/styled&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Structuring the directory
&lt;/h2&gt;

&lt;p&gt;As our setup is done, now is the time for developing the actual project. &lt;br&gt;
For that, I usually start with making some directory structure. &lt;br&gt;
Below is the directory structure I made for this project:&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%2F0hwnexwxh5zimrympikq.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%2F0hwnexwxh5zimrympikq.png" alt=" " width="318" height="364"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It is not necessary to make the directory structure at the start of the project. Directory structure is always being updated as the project grows.&lt;/p&gt;
&lt;h2&gt;
  
  
  Adding Dummy Data
&lt;/h2&gt;

&lt;p&gt;As we are only on the front-end, i.e without any back-end, we would need to create the dummy data.&lt;/p&gt;

&lt;p&gt;But before that, we need to make an interface which corresponds to dummy data. An interface defines the syntax that any entity must adhere to. (Definition from &lt;a href="https://www.tutorialspoint.com/typescript/typescript_interfaces.htm" rel="noopener noreferrer"&gt;tutorialspoint&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;So make a file in '/commonInterfaces' by name &lt;code&gt;index.ts&lt;/code&gt; and copy paste the interface below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export interface TodoListProps {
    id: number,
    checked: boolean,
    title: string,
    description: string
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As interfaces provides a syntax, so it should be having the attributes which our object have. In this case, we know that todo would have &lt;code&gt;title as string&lt;/code&gt;, &lt;code&gt;description as string&lt;/code&gt;, &lt;code&gt;checked as boolean&lt;/code&gt; and finally the &lt;code&gt;id as number&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Moving on to adding Dummy Data&lt;br&gt;
So in '/dummydata' directory, make a file named &lt;code&gt;index.ts&lt;/code&gt; and paste the dummy data provided below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { TodoListProps } from "../commonInterfaces";

export const DummyTodoList: TodoListProps[] = [
    {
        id: 1,
        checked: false,
        title: 'Todo 1',
        description: 'This is Todo 1'
    },
    {
        id: 2,
        checked: false,
        title: 'Todo 2',
        description: 'This is Todo 2'
    },
    {
        id: 3,
        checked: false,
        title: 'Todo 3',
        description: 'This is Todo 3'
    },
    {
        id: 4,
        checked: true,
        title: 'Todo 4',
        description: 'This is Todo 4'
    },
    {
        id: 5,
        checked: true,
        title: 'Todo 5',
        description: 'This is Todo 5'
    },
]

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Making Todo Page
&lt;/h2&gt;

&lt;p&gt;Now, it's time to make a todo page which will be a wrapper for all todo related components&lt;/p&gt;

&lt;p&gt;So make a directory in '/pages' by name 'todo' and make a file in '/pages/todo/' by name 'index.tsx'. &lt;/p&gt;

&lt;h4&gt;
  
  
  Styled Components
&lt;/h4&gt;

&lt;p&gt;First, let's make the styled component as wrapper:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { styled } from "@mui/material";
const FlexCenter = styled('div')(() =&amp;gt; ({
    display: 'flex',
    justifyContent: 'center',
    width: '100%'
}))

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

&lt;/div&gt;



&lt;p&gt;Now, let's make the styled component of the title:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Title = styled('h1')( ({theme}) =&amp;gt; ({
    color: theme.palette.primary.main 
}))

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

&lt;/div&gt;



&lt;p&gt;If you do not know what are styled components and how to make them, you can read it on &lt;a href="https://mui.com/system/styled/" rel="noopener noreferrer"&gt;MUI documentation&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Styled component is just another way of writing css for the component.&lt;/p&gt;

&lt;h4&gt;
  
  
  Making Todo Page Component
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const TodoPage = () =&amp;gt; {

    return(
        &amp;lt;Grid container sx = {{px: 1, justifyContent: 'space-around'}}&amp;gt;
            &amp;lt;Grid item xs = {5}&amp;gt;
                &amp;lt;FlexCenter&amp;gt;
                    &amp;lt;div style = {{width: '100%'}}&amp;gt;
                        &amp;lt;Title&amp;gt;
                            Todo
                        &amp;lt;/Title&amp;gt;
                        {todoList.filter(el =&amp;gt; el.checked == false).map((el)=&amp;gt;{
                            return(
                                &amp;lt;TodoCardComponent key = {el.id} {...el} toggleCheck={toggleCheck} deleteTodo = {deleteTodo} isEditing = {el.id == editIndex} setEditIndex={setEditIndex} saveEdit = {saveEdit}/&amp;gt;
                            )
                        })}
                    &amp;lt;/div&amp;gt;
                &amp;lt;/FlexCenter&amp;gt;
            &amp;lt;/Grid&amp;gt;
            &amp;lt;Grid item xs = {5}&amp;gt;
                &amp;lt;FlexCenter&amp;gt;
                    &amp;lt;div style = {{width: '100%'}}&amp;gt;
                        &amp;lt;Title&amp;gt;
                            Done
                        &amp;lt;/Title&amp;gt;
                        {todoList.filter(el =&amp;gt; el.checked == true).map((el)=&amp;gt;{
                            return(
                                &amp;lt;TodoCardComponent key = {el.id} {...el} toggleCheck={toggleCheck} deleteTodo = {deleteTodo} isEditing = {el.id == editIndex} setEditIndex={setEditIndex} saveEdit = {saveEdit}/&amp;gt;
                            )
                        })}
                    &amp;lt;/div&amp;gt;
                &amp;lt;/FlexCenter&amp;gt;
            &amp;lt;/Grid&amp;gt;
        &amp;lt;/Grid&amp;gt;
    )
} 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we made the component but many things are missing from it. You can see that we are using the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;todoList/setTodoList, a state responsible for storing the current todo list&lt;/li&gt;
&lt;li&gt;editIndex/setEditIndex, a state responsible for storing the index of the todo item which is currently being in edit mode, if none is in edit mode, it would be -1&lt;/li&gt;
&lt;li&gt;toggleCheck, a funciton responsible to update the checked/unchecked status of a single todo&lt;/li&gt;
&lt;li&gt;deleteTodo, a fucntion responsible for deleting a single todo&lt;/li&gt;
&lt;li&gt;saveEdit, a funciton responsible for saving the edited todo&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These were never defined but us, but used in the above code. Through these, we will achieve the functionality of our Todo App so let's define these. Below is the whole file with all these missing items. So you can copy paste the below code into &lt;code&gt;/pages/todo/index.tsx&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 { Grid, styled } from "@mui/material";
import { useCallback, useState } from "react";
import { DummyTodoList } from "../../dummydata";
import { TodoCardComponent } from "../../components/todoCard";


const FlexCenter = styled('div')(() =&amp;gt; ({
    display: 'flex',
    justifyContent: 'center',
    width: '100%'
}))

const Title = styled('h1')( ({theme}) =&amp;gt; ({
    color: theme.palette.primary.main 
}))



export const TodoPage = () =&amp;gt; {

    const [todoList, setTodoList] = useState(DummyTodoList)
    const [editIndex, setEditIndex] = useState(-1)

    const toggleCheck = useCallback((id: number) =&amp;gt; {
        const tempTodoList = todoList
        const index = tempTodoList.findIndex(e =&amp;gt; e.id == id)
        tempTodoList[index].checked = !tempTodoList[index].checked
        setTodoList([...tempTodoList])
    }, [todoList])

    const deleteTodo = useCallback((id: number) =&amp;gt; {
        let tempTodoList = todoList
        tempTodoList = tempTodoList.filter(el =&amp;gt; el.id != id)
        setTodoList([...tempTodoList])
    }, [todoList])

    const saveEdit = useCallback((id: number, title: string, description: string) =&amp;gt; {
        const tempTodoList = todoList
        const index = tempTodoList.findIndex(e =&amp;gt; e.id == id)
        tempTodoList[index].title = title
        tempTodoList[index].description = description
        setTodoList([...tempTodoList])
        setEditIndex(-1)
    }, [todoList])

    return(
        &amp;lt;Grid container sx = {{px: 1, justifyContent: 'space-around'}}&amp;gt;
            &amp;lt;Grid item xs = {5}&amp;gt;
                &amp;lt;FlexCenter&amp;gt;
                    &amp;lt;div style = {{width: '100%'}}&amp;gt;
                        &amp;lt;Title&amp;gt;
                            Todo
                        &amp;lt;/Title&amp;gt;
                        {todoList.filter(el =&amp;gt; el.checked == false).map((el)=&amp;gt;{
                            return(
                                &amp;lt;TodoCardComponent key = {el.id} {...el} toggleCheck={toggleCheck} deleteTodo = {deleteTodo} isEditing = {el.id == editIndex} setEditIndex={setEditIndex} saveEdit = {saveEdit}/&amp;gt;
                            )
                        })}
                    &amp;lt;/div&amp;gt;
                &amp;lt;/FlexCenter&amp;gt;
            &amp;lt;/Grid&amp;gt;
            &amp;lt;Grid item xs = {5}&amp;gt;
                &amp;lt;FlexCenter&amp;gt;
                    &amp;lt;div style = {{width: '100%'}}&amp;gt;
                        &amp;lt;Title&amp;gt;
                            Done
                        &amp;lt;/Title&amp;gt;
                        {todoList.filter(el =&amp;gt; el.checked == true).map((el)=&amp;gt;{
                            return(
                                &amp;lt;TodoCardComponent key = {el.id} {...el} toggleCheck={toggleCheck} deleteTodo = {deleteTodo} isEditing = {el.id == editIndex} setEditIndex={setEditIndex} saveEdit = {saveEdit}/&amp;gt;
                            )
                        })}
                    &amp;lt;/div&amp;gt;
                &amp;lt;/FlexCenter&amp;gt;
            &amp;lt;/Grid&amp;gt;
        &amp;lt;/Grid&amp;gt;
    )
} 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are using TodoCardComponent in the above component, but we never made it. So let's make it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Making of Todo Card Component
&lt;/h2&gt;

&lt;p&gt;We need to make a component which will be responsible to render the single todo. By doing this, we will be able reuse this component for all the list of todo.&lt;/p&gt;

&lt;p&gt;So make a folder in '/components' named 'todoCard', i.e it would become: '/components/todoCard/'. Here make a new file named 'index.jsx' with 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 { Button, Card, Checkbox, Grid, TextField, Typography, styled } from "@mui/material";
import { useRef } from "react";
import { TodoListProps } from "../../commonInterfaces";


const CustomCard = styled(Card)(({ theme }) =&amp;gt; ({
    padding: theme.spacing(1),
    borderRadius: theme.shape.borderRadius,
    width: '100%',
    marginBottom: theme.spacing(1),
    marginTop: theme.spacing(1)
}));

interface TodoCardProps extends TodoListProps {
    toggleCheck(id: number): void,
    deleteTodo(id: number): void,
    setEditIndex(id: number): void,
    saveEdit(id: number, title: string, description: string): void,
    isEditing: boolean
}



export const TodoCardComponent = ({id, checked, title, description, toggleCheck, deleteTodo, isEditing, setEditIndex, saveEdit}: TodoCardProps) =&amp;gt; {

    const titleRef = useRef&amp;lt;HTMLInputElement&amp;gt;(null)
    const descriptionRef = useRef&amp;lt;HTMLInputElement&amp;gt;(null)

    return(
        &amp;lt;CustomCard elevation={3}&amp;gt;
            &amp;lt;Grid container&amp;gt;
                &amp;lt;Grid item&amp;gt;
                    &amp;lt;Checkbox onChange={()=&amp;gt;{toggleCheck(id)}} checked = {checked}&amp;gt;&amp;lt;/Checkbox&amp;gt;
                &amp;lt;/Grid&amp;gt;
                &amp;lt;Grid item xs = {8}&amp;gt;
                    {!isEditing ?
                        &amp;lt;&amp;gt;
                            &amp;lt;Typography variant = 'h6' style = {{textDecoration: checked ? 'line-through' : 'none', color: checked ? 'lightgray' : 'black'}}&amp;gt;
                                {title}
                            &amp;lt;/Typography&amp;gt;
                            &amp;lt;Typography variant = 'body1' style = {{textDecoration: checked ? 'line-through' : 'none', color: checked ? 'lightgray' : 'black'}}&amp;gt;
                                {description}
                            &amp;lt;/Typography&amp;gt;
                            &amp;lt;Button onClick = {()=&amp;gt;{setEditIndex(id)}} variant = 'contained' color = 'info' sx = {{marginBottom: 1}}&amp;gt;
                                Edit
                            &amp;lt;/Button&amp;gt;
                        &amp;lt;/&amp;gt;
                        :
                        &amp;lt;&amp;gt;
                            &amp;lt;TextField inputRef = {titleRef} defaultValue={title} sx = {{marginBottom: 1}}/&amp;gt;
                            &amp;lt;TextField inputRef = {descriptionRef} defaultValue={description} sx = {{marginBottom: 1}}/&amp;gt;
                            &amp;lt;br/&amp;gt;
                            &amp;lt;Button onClick={()=&amp;gt;{if(titleRef.current &amp;amp;&amp;amp; descriptionRef.current)saveEdit(id, titleRef.current.value, descriptionRef.current.value)}} variant = 'contained' color = 'success' sx = {{marginBottom: 1}}&amp;gt;
                                Save
                            &amp;lt;/Button&amp;gt;
                            &amp;lt;br/&amp;gt;
                            &amp;lt;Button onClick={()=&amp;gt;{setEditIndex(-1)}} variant = 'contained' color = 'warning'&amp;gt;
                                Discard
                            &amp;lt;/Button&amp;gt;
                        &amp;lt;/&amp;gt;
                    }
                &amp;lt;/Grid&amp;gt;
                {!isEditing &amp;amp;&amp;amp;
                    &amp;lt;Grid item xs = {2}&amp;gt;
                        &amp;lt;Button variant="contained" onClick={()=&amp;gt;{deleteTodo(id)}} color="error"&amp;gt;
                            Delete
                        &amp;lt;/Button&amp;gt;
                    &amp;lt;/Grid&amp;gt;
                }
            &amp;lt;/Grid&amp;gt;
        &amp;lt;/CustomCard&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Rendering the Todo Page in App.tsx
&lt;/h2&gt;

&lt;p&gt;Finally we need to render our page in so that it can be shown to us in '/' path.&lt;br&gt;
Open 'App.tsx' and paste the 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;import { TodoPage } from "./pages/todo"
import './App.css'

function App() {

  return (
    &amp;lt;TodoPage/&amp;gt;
  )
}

export default App

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

&lt;/div&gt;



&lt;p&gt;That's it. Now our Todo Page component will get rendered at '/' path. &lt;br&gt;
Now run the dev server by &lt;code&gt;npm run dev&lt;/code&gt; if it is not already running and open the browser and type: &lt;code&gt;localhost:5173&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This is what it should look like:&lt;br&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%2Fzcba9ocnffmij60qojq4.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%2Fzcba9ocnffmij60qojq4.png" alt=" " width="800" height="405"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Assignment
&lt;/h2&gt;

&lt;p&gt;Notice that I have not added the 'Create New todo' feature in this app. Play around the code and try to make it yourself.&lt;/p&gt;

&lt;h2&gt;
  
  
  Repository Link
&lt;/h2&gt;

&lt;p&gt;Here is the &lt;a href="https://github.com/kito-arch/React-Typescript-Todo-App" rel="noopener noreferrer"&gt;repo&lt;/a&gt; from which you can clone the project and play around. &lt;/p&gt;




&lt;p&gt;Hope it helped you understanding the basics. Keep learning. ❤️&lt;/p&gt;

</description>
      <category>react</category>
      <category>typescript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to integrate Paypal with NextJs</title>
      <dc:creator>Husnain Mustafa</dc:creator>
      <pubDate>Mon, 03 Jul 2023 09:06:36 +0000</pubDate>
      <link>https://forem.com/husnain/how-to-integrate-paypal-with-nextjs-2oil</link>
      <guid>https://forem.com/husnain/how-to-integrate-paypal-with-nextjs-2oil</guid>
      <description>&lt;p&gt;Payment integration is the most required thing when we are heading to develop a an eCommerce website. And Paypal is one of the most common platforms which allow us to make our transactions smoothly. So let's learn how we can integrate Paypal with our NextJs eCommerce App.&lt;/p&gt;

&lt;h2&gt;
  
  
  Installing the required packages
&lt;/h2&gt;

&lt;p&gt;First, we need some packages which will help us a lot in the integration of Paypal and we would just need to use those according to our need.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://www.npmjs.com/package/@paypal/react-paypal-js" rel="noopener noreferrer"&gt;@paypal/react-paypal-js&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.npmjs.com/package/@paypal/checkout-server-sdk" rel="noopener noreferrer"&gt;@paypal/checkout-server-sdk&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  @paypal/react-paypal-js
&lt;/h4&gt;

&lt;p&gt;For the front-end, where we need Paypal Payment Buttons to be shown and the functionality of:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Creating an order&lt;/li&gt;
&lt;li&gt;Capturing an order&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This package will help us in those requriements&lt;/p&gt;

&lt;h4&gt;
  
  
  @paypal/checkout-server-sdk
&lt;/h4&gt;

&lt;p&gt;For the back-end, where we actually need to call the paypal Api, this package provides us classes which are helpful in that.&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Credentials and Setting Environment
&lt;/h2&gt;

&lt;p&gt;Head over to &lt;a href="https://developer.paypal.com/" rel="noopener noreferrer"&gt;Paypal Developer&lt;/a&gt; and create and account.&lt;br&gt;
Once you are on the dashboard:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Click on 'Sandbox Accounts':&lt;br&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%2Fc3ipaz1mwxrdpz0a42j6.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%2Fc3ipaz1mwxrdpz0a42j6.png" alt=" " width="800" height="357"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Scroll down and view the details of &lt;strong&gt;business&lt;/strong&gt; account:&lt;br&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%2Fam0ft6n65pcfmjut8359.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%2Fam0ft6n65pcfmjut8359.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Under &lt;strong&gt;Rest Api Apps&lt;/strong&gt;, Copy the &lt;strong&gt;Cliend ID&lt;/strong&gt; and &lt;strong&gt;Secret&lt;/strong&gt; and store those in your app in .env file&lt;br&gt;
If you are unable to find these things under &lt;strong&gt;Rest Api Apps&lt;/strong&gt;, you need to create an app by clicking the button, &lt;strong&gt;Create App&lt;/strong&gt;. When popup is shown, select &lt;strong&gt;Merchant&lt;/strong&gt; account.&lt;br&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%2Fsh4lma5m6naral3iog9x.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%2Fsh4lma5m6naral3iog9x.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;.env&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;PAYPAL_CLIENT_ID = "&amp;lt;your cliend id&amp;gt;"
PAYPAL_CLIENT_SECRET = "&amp;lt;your client secret&amp;gt;"
NEXT_PUBLIC_PAYPAL_CLIENT_ID = "&amp;lt;your client id&amp;gt;"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: We are using sandbox account for this tutorial purpose. You can easily switch to live account by replacing the sandbox credentials, cliend ID and Secret, with Live one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Back-end Integration
&lt;/h2&gt;

&lt;p&gt;We need to define api endpoints through which we will create and capture order from the front-end.&lt;/p&gt;

&lt;p&gt;We need to define two endpoints, one for creating an order, other for capturing an order.&lt;/p&gt;

&lt;p&gt;But before that, we need to make a &lt;strong&gt;client&lt;/strong&gt; with our required configuration. This client will help us call Paypal Api to create and capture orders. So make a file in &lt;/p&gt;

&lt;p&gt;/utils/paypal/index.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 checkoutNodeJssdk from '@paypal/checkout-server-sdk'

const configureEnvironment = function () {
  const clientId = process.env.PAYPAL_CLIENT_ID
  const clientSecret = process.env.PAYPAL_CLIENT_SECRET

  return process.env.NODE_ENV === 'production'
    ? new checkoutNodeJssdk.core.LiveEnvironment(clientId, clientSecret)
    : new checkoutNodeJssdk.core.SandboxEnvironment(clientId, clientSecret)
}

const client = function () {
  return new checkoutNodeJssdk.core.PayPalHttpClient(configureEnvironment())
}

export default client
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have configured our client to use the client ID and client secret that we defined earlier in .env file. These client ID and client secret are required by Paypal to create and capture order.&lt;/p&gt;

&lt;p&gt;Now back to our api endpoints.&lt;br&gt;
/api/paypal/createorder.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 client from 'backend/paypal'
import paypal from '@paypal/checkout-server-sdk'

...
...

export default async function Handler(req, res) {

  if(req.method != "POST")
    return res.status(404).json({success: false, message: "Not Found"})

  if(!req.body.order_price || !req.body.user_id)
    return res.status(400).json({success: false, message: "Please Provide order_price And User ID"})


  try{
    const PaypalClient = client()
    //This code is lifted from https://github.com/paypal/Checkout-NodeJS-SDK
    const request = new paypal.orders.OrdersCreateRequest()
    request.headers['prefer'] = 'return=representation'
    request.requestBody({
      intent: 'CAPTURE',
      purchase_units: [
        {
          amount: {
            currency_code: 'USD',
            value: req.body.order_price+"",
          },
        },
      ],
    })
    const response = await PaypalClient.execute(request)
    if (response.statusCode !== 201) {
      console.log("RES: ", response)
      return res.status(500).json({success: false, message: "Some Error Occured at backend"})
    }

    ...

    // Your Custom Code for doing something with order
    // Usually Store an order in the database like MongoDB

    ...   

    res.status(200).json({success: true, data: {order}})
  } 
  catch(err){
    console.log("Err at Create Order: ", err)
    return res.status(500).json({success: false, message: "Could Not Found the user"})
  }

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

&lt;/div&gt;



&lt;p&gt;/api/paypal/captureorder.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 client from 'backend/paypal'
import paypal from '@paypal/checkout-server-sdk'


...

export default async function Handler(req, res) {

  if(req.method != "POST")
    return res.status(404).json({success: false, message: "Not Found"})

  if(!req.body.orderID)
    return res.status(400).json({success: false, message: "Please Provide Order ID"})

  //Capture order to complete payment
  const { orderID } = req.body
  const PaypalClient = client()
  const request = new paypal.orders.OrdersCaptureRequest(orderID)
  request.requestBody({})
  const response = await PaypalClient.execute(request)
  if (!response) {
    return res.status(500).json({success: false, message: "Some Error Occured at backend"})
  }

  ...

  // Your Custom Code to Update Order Status
  // And Other stuff that is related to that order, like wallet
  // Here I am updateing the wallet and sending it back to frontend to update it on frontend

  ...

  res.status(200).json({success: true, data: {wallet}})
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Front-end Integration
&lt;/h2&gt;

&lt;p&gt;Now open a component where you need to show the Paypal Payment Buttons. &lt;br&gt;
Import the following:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;import { PayPalScriptProvider, PayPalButtons } from '@paypal/react-paypal-js'&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Move over to the 'return' statement and add the Paypal Payment Buttons by:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
   ...
   ...

   &amp;lt;PayPalScriptProvider
            options={{
              'client-id': process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID,
              currency: 'USD',
              intent: 'capture'
            }}
          &amp;gt;
            &amp;lt;PayPalButtons
              style={{
                color: 'gold',
                shape: 'rect',
                label: 'pay',
                height: 50
              }}
              createOrder={async (data, actions) =&amp;gt; {
                let order_id = await paypalCreateOrder()
                return order_id + ''
              }}
              onApprove={async (data, actions) =&amp;gt; {
                let response = await paypalCaptureOrder(data.orderID)
                if (response) return true
              }}
            /&amp;gt;
          &amp;lt;/PayPalScriptProvider&amp;gt;

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

&lt;/div&gt;



&lt;p&gt;You can alter the currency and styles of the buttons.&lt;br&gt;
As you can see in the code, we are calling 'paypalCreateOrder' in 'createOrder' and 'paypalCaptureOrder' in 'onApprove'. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;createOrder&lt;/strong&gt; is where we need to define a function which must return an &lt;strong&gt;order id&lt;/strong&gt; of the generated order in Paypal.&lt;br&gt;
For that we are defining another function &lt;strong&gt;paypalCaptureOrder&lt;/strong&gt; which will call our backend api and return order id of generated order.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;onApprove&lt;/strong&gt; is where we define a function which is called when our payment is approved. Here we will call our backend api to capture the order and to update the &lt;strong&gt;wallet&lt;/strong&gt; and &lt;strong&gt;order status&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;paypalCreateOrder:&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;   ...
   ...

   const paypalCreateOrder = async () =&amp;gt; {
    try {
      let response = await axios.post('/api/paypal/createorder', {
        user_id: store.getState().auth.user._id,
        order_price: amountRef.current.value
      })
      return response.data.data.order.order_id
    } catch (err) {
      // Your custom code to show an error like showing a toast:
      // toast.error('Some Error Occured')
      return null
    }
  }

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;paypalCreateOrder&lt;/strong&gt; is the function which will call our backend api which is responsible for creating an order in Paypal.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;paypalCaptureOrder:&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;   ...
   ...

   const paypalCaptureOrder = async orderID =&amp;gt; {
    try {
      let response = await axios.post('/api/paypal/captureorder', {
        orderID
      })
      if (response.data.success) {
        // Order is successful
        // Your custom code

        // Like showing a success toast:
        // toast.success('Amount Added to Wallet')

        // And/Or Adding Balance to Redux Wallet
        // dispatch(setWalletBalance({ balance: response.data.data.wallet.balance }))
    } catch (err) {
      // Order is not successful
      // Your custom code

      // Like showing an error toast
      // toast.error('Some Error Occured')
    }
  }

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;paypalCaptureOrder&lt;/strong&gt; is the function which will call our backend api which is responsible for capturing an order, i.e fulfilling an order, in Paypal.&lt;/p&gt;

&lt;p&gt;Our Buttons will look like this:&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%2Fhpaed0t4ym2of9fqu6o9.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%2Fhpaed0t4ym2of9fqu6o9.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Don't forget to replace the back-end endpoints with your back-end api endpoints in these two functions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing
&lt;/h2&gt;

&lt;p&gt;Now you can test the paypal integration with sandbox personal account's email and password which you will find in:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Sandbox Accounts:&lt;br&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%2Fwro7aguqwmxaj138wgyj.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%2Fwro7aguqwmxaj138wgyj.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Under Accounts, select Personal Account:&lt;br&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%2Fmibfn54clpoqywk3fttw.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%2Fmibfn54clpoqywk3fttw.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Finally use the credentials to make the payment:&lt;br&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%2Fq7qyy0kvoj6nmo98dxx5.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%2Fq7qyy0kvoj6nmo98dxx5.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;That's all&lt;br&gt;
If you got any questions, feel free to ask.&lt;/p&gt;

</description>
      <category>tutorial</category>
      <category>paypal</category>
      <category>react</category>
      <category>node</category>
    </item>
  </channel>
</rss>
