<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Shahid Rizwan</title>
    <description>The latest articles on DEV Community by Shahid Rizwan (@shaedrizwan).</description>
    <link>https://dev.to/shaedrizwan</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%2F698770%2F38bbb2e1-efed-4635-89ca-a71286d81f11.jpg</url>
      <title>DEV Community: Shahid Rizwan</title>
      <link>https://dev.to/shaedrizwan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/shaedrizwan"/>
    <language>en</language>
    <item>
      <title>Promise in Javascript</title>
      <dc:creator>Shahid Rizwan</dc:creator>
      <pubDate>Thu, 09 Sep 2021 17:36:53 +0000</pubDate>
      <link>https://dev.to/shaedrizwan/promise-in-javascript-56jo</link>
      <guid>https://dev.to/shaedrizwan/promise-in-javascript-56jo</guid>
      <description>&lt;p&gt;A promise is one of the most confusing concepts in javascript for someone new to Javascript. It may look quite complicated to understand at first sight, but it is quite simple and is not rocket science.&lt;/p&gt;

&lt;p&gt;Promise in javascript is similar to promise in real life, like how we promise to do a task like cleaning the room, it is a guarantee that we are going to do something in the future.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why do we need Promise?
&lt;/h2&gt;

&lt;p&gt;Before Promise, callback functions were used for performing asynchronous operations. Since it was confusing and had limitations in functionality, Promise was introduced in ES6. &lt;/p&gt;

&lt;p&gt;If there are multiple asynchronous operations to be done and if we try to use good-old Callbacks for them, we’ll find ourselves quickly inside a situation called Callback hell. &lt;/p&gt;

&lt;h3&gt;
  
  
  A simple promise function
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let promise = new Promise((resolve, reject) =&amp;gt; { 
  let task_performed = true;
  if(task_performed) { 
    resolve('Success!'); 
  } else { 
    reject('Failed!'); 
  } 
}); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Different states of Promise
&lt;/h2&gt;

&lt;p&gt;The 3 states of promise object are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pending&lt;/li&gt;
&lt;li&gt;Resolved&lt;/li&gt;
&lt;li&gt;Rejected&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Pending:&lt;/strong&gt; It is the initial state of the Promise before Promise succeeds or fails. When we request data from the server by using a Promise, it will be in pending mode until we receive our data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resolved:&lt;/strong&gt; It is the state where a promise is fulfilled successfully. It's like when we use a promise to get data from the server, we get the resolved state when the data is successfully received.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Rejected:&lt;/strong&gt; It is the state where a promise is not fulfilled due to some error.&lt;/p&gt;

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

&lt;p&gt;The .then() method is called after a promise is resolved. We can use it to decide what to do with the resolved promise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let promise = new Promise((resolve, reject) =&amp;gt; { 
  let task_performed = true;
  if(task_performed) { 
    resolve('Success!'); 
  } else { 
    reject('Failed!'); 
  } 
}); 

promise.then((response) =&amp;gt; console.log(response))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We also know that not all Promises will be resolved every time. What if the promise gets rejected? We use the .catch() method after a promise is rejected. It can be used for throwing a new error or logging the details to the console.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let promise = new Promise((resolve, reject) =&amp;gt; { 
  let task_performed = true;
  if(task_performed) { 
    resolve('Success!'); 
  } else { 
    reject('Failed!'); 
  } 
}); 

promise.then((response) =&amp;gt; console.log(response))
.catch((error) =&amp;gt; console.log(error))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Set your Web App to Dark/Light Mode based on User System Settings</title>
      <dc:creator>Shahid Rizwan</dc:creator>
      <pubDate>Sun, 05 Sep 2021 17:17:18 +0000</pubDate>
      <link>https://dev.to/shaedrizwan/set-your-web-app-to-dark-light-mode-based-on-user-system-settings-5fa6</link>
      <guid>https://dev.to/shaedrizwan/set-your-web-app-to-dark-light-mode-based-on-user-system-settings-5fa6</guid>
      <description>&lt;p&gt;We all know Dark mode is one of the hottest features from 2019. Everything from smartphones, laptops, and your applications now comes with in-build dark mode.&lt;/p&gt;

&lt;p&gt;It comes with a lot of advantages. It's the way forward when spending long hours in front of the laptop under low light.&lt;/p&gt;

&lt;p&gt;It also saves significant battery in newer devices using OLED screens by turning off the black pixels.&lt;/p&gt;

&lt;p&gt;But, is it the best option to choose all the time over light mode? Let's see.&lt;/p&gt;

&lt;h2&gt;
  
  
  The dark mode comes with some disadvantages too.
&lt;/h2&gt;

&lt;p&gt;Using dark mode when the surrounding is well lit can cause strain to your eyes just like when you use too much light in low light condition. When in the bright surrounding, your eye finds it hard to focus on the content present in the dark background with very little contrast. Therefore, most users switch between dark and light modes in their devices based on their surroundings.&lt;/p&gt;

&lt;p&gt;What if, we as developers, can set our web application theme based on the device settings and reduce that extra step to switch in our apps? Will it be possible?&lt;br&gt;
Well, there is a way.&lt;/p&gt;
&lt;h2&gt;
  
  
  What is Window.matchMedia() ?
&lt;/h2&gt;

&lt;p&gt;Windows.matchMedia() is a method that returns an object that determines if the document matches the media query string. &lt;/p&gt;

&lt;p&gt;Just like how we use @media in CSS, you can detect the same media queries in javascript.&lt;/p&gt;

&lt;p&gt;For example, if we have the following media query in CSS&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@media screen and (max-width:700px){
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The javascript equivalent is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mw = window.matchMedia("screen and (max-width:700px)")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Detecting System theme using matchMedia()
&lt;/h2&gt;

&lt;p&gt;Consider a simple React component with a Hello World text written in it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {


  return (
    &amp;lt;div&amp;gt;
      Hello World
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;To add the dark mode to the component, we use the prefers-color-scheme CSS media feature. It detects if the system is in a dark theme or light theme.&lt;/p&gt;

&lt;p&gt;The matches property of the prefers-color-scheme is a boolean value that updates based on the query.&lt;/p&gt;

&lt;p&gt;So, to check the system preference, we add as isDark variable to detect if the system uses dark mode.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {

  const isDark = window.matchMedia("(prefers-color-scheme:dark)").matches

  const lightTheme = {
    backgroundColor : "white",
    color : "black"
  }

  const darkTheme = {
    backgroundColor : "black",
    color : "white"
  }

  return (
    &amp;lt;div style={isDark?darkTheme:lightTheme}&amp;gt;
      Hello World
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;Based on the isDark variable value, either the darkTheme or lightTheme syle applies to the component.&lt;/p&gt;

&lt;h2&gt;
  
  
  Option to Switch themes inside the application
&lt;/h2&gt;

&lt;p&gt;We can also add a toggle inside the application if the user wants to switch between the themes.&lt;/p&gt;

&lt;p&gt;For that, we create a state variable and initialize it with the system theme settings.&lt;/p&gt;

&lt;p&gt;Every time the user clicks the button, the state variable toggles accordingly.&lt;br&gt;
&lt;/p&gt;

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

function App() {

  const isSystemDark = window.matchMedia("(prefers-color-scheme: dark)").matches
  const [isDark,setIsDark] = useState(isSystemDark)

  const lightTheme = {
    backgroundColor : "white",
    color : "black"
  }

  const darkTheme = {
    backgroundColor : "black",
    color : "white"
  }

  return (
    &amp;lt;div style={isDark?darkTheme:lightTheme}&amp;gt;
      Hello World
      &amp;lt;button onClick={()=&amp;gt;setIsDark(toggle =&amp;gt;!toggle)}&amp;gt;Switch Theme&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

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

&lt;/div&gt;



</description>
      <category>react</category>
      <category>tutorial</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Building custom hooks in React to fetch Data</title>
      <dc:creator>Shahid Rizwan</dc:creator>
      <pubDate>Sat, 04 Sep 2021 08:02:10 +0000</pubDate>
      <link>https://dev.to/shaedrizwan/building-custom-hooks-in-react-to-fetch-data-4ig6</link>
      <guid>https://dev.to/shaedrizwan/building-custom-hooks-in-react-to-fetch-data-4ig6</guid>
      <description>&lt;p&gt;Fetching data from the backend is one of the crucial parts of the web application. For every application to work dynamically, it fetches the data from the server and then displays it in the user interface.&lt;/p&gt;

&lt;p&gt;We retrieve the data using the API call and using built-in React hooks like useState, useEffect, and useReducer, the retrieved data is set to the state variable. It is then used in components for showing it in the view.&lt;/p&gt;

&lt;p&gt;Before jumping into the code of how's it's done, let's first look at what React hooks are and why it is used.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is React Hooks
&lt;/h2&gt;

&lt;p&gt;React hooks were first introduced in React 16.8. They are functions that let you hook into React state.&lt;/p&gt;

&lt;p&gt;Some of the built-in hooks provided by React are useState, useEffect, useContext, useReducer, useRef, useCallback, and useMemo.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why React Hooks are used
&lt;/h2&gt;

&lt;p&gt;One of the main advantages of using React hooks is the re-usability of logic. The hooks can be used in multiple components where we have to use a specific function.&lt;/p&gt;

&lt;p&gt;It also makes the code more readable, efficient, and easy to maintain.&lt;/p&gt;

&lt;p&gt;The normal code for fetching the data from the server and updating in the component is shown below&lt;/p&gt;

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

export function Home(){

    const [data,setData] = useState(null)
    const [loading,setLoading] = useState(false)
    const [error,setError] = useState(null)

    useEffect(()=&amp;gt;{
        (
        async function(){
            try{
                setLoading(true)
                const response = await axios.get('http:localhost:4000')
                setData(response.data)
            }
            catch(err){
                setError(err)
            }finally{
                setLoading(false)
            }
        }
        )()
    },[])

    return(
        {loading &amp;amp;&amp;amp; &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;}
        {data &amp;amp;&amp;amp; &amp;lt;div&amp;gt;{data}&amp;lt;/div&amp;gt;
    )
}


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

&lt;/div&gt;

&lt;p&gt;We write the logic inside the useEffect hook to update the state properties like data, loading, and error.&lt;/p&gt;

&lt;p&gt;While it's perfectly fine to write like this, what if we want to do the same kind of thing in multiple components where we have to fetch another data.&lt;/p&gt;

&lt;p&gt;We have to rewrite all of these codes multiple times in all of those components which is not very efficient and hard to manage.&lt;/p&gt;

&lt;p&gt;In big codebases, it is better to follow the Don't Repeat Yourself (DRY) principles, that is, it's better to write code once and make it reusable instead of writing it again and again in multiple components.&lt;/p&gt;

&lt;p&gt;That's where the real magic of Custom Hook is. We can write the code in a separate js file and call it with URL from all the components that might need to fetch the data from the server.&lt;/p&gt;

&lt;p&gt;This makes the code efficient and easily maintainable.&lt;/p&gt;

&lt;p&gt;Like useState and useEffect have their function, we create custom hooks by combining them for a specific ability.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating custom useFetch hook
&lt;/h2&gt;

&lt;p&gt;We first create a new javascript file with the name useFetch.js.&lt;br&gt;
The name of the hooks starts with use as a part of react hooks convention.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl8ipnu7lhb7tmd0mcfu1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl8ipnu7lhb7tmd0mcfu1.png" alt="useFetch javascript file"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Inside the file, create a new function with the name of the hook. The difference between React hook and a React component is that hook doesn't return JSX. It only returns the state variable or function that you want to use in a component.&lt;/p&gt;

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

export function useFetch(){

}


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

&lt;/div&gt;

&lt;p&gt;To make an API call, use a useEffect hook because it will trigger the API call function inside it when rendered. Here, the API call is made using Axios.&lt;/p&gt;

&lt;p&gt;The API Url that needs to be called is passed to the hook as an argument from the component.&lt;/p&gt;

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

import { useEffect } from "react"
import axios from axios

export function useFetch(url){
   useEffect(()=&amp;gt;{
      (
         async function(){
            const response = await axios.get(url)
         }
      )()
   },[url])

}


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

&lt;/div&gt;

&lt;p&gt;Usually, we have 3 state variables that are data, error, and loading created using useState to store the response data, error and loading respectively,&lt;/p&gt;

&lt;p&gt;If the data is received, we set it to the data variable. If not, the error message will be set to the error variable.&lt;/p&gt;

&lt;p&gt;Loader is initialized as false. When the API is called, it is set to true so that a loader component can be loaded in the view.&lt;/p&gt;

&lt;p&gt;At the end of the API call, this loader is set back to false by using the finally block.&lt;/p&gt;

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

import { useEffect, useState } from "react"
import axios from "axios"


export default function useFetch(url){

    const [data,setData] = useState(null)
    const [error,setError] = useState(null)
    const [loading,setLoading] = useState(false)

    useEffect(() =&amp;gt; {
        (
            async function(){
                try{
                    setLoading(true)
                    const response = await axios.get(url)
                    setData(response.data)
                }catch(err){
                    setError(err)
                }finally{
                    setLoading(false)
                }
            }
        )()
    }, [url])

    return { data, error, loading }

}


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

&lt;/div&gt;

&lt;p&gt;The only dependency we're going to put in the useEffect dependency array is Url because if the Url changes, we have to request new data.&lt;/p&gt;

&lt;p&gt;That's basically for useEffect. Now we return the states that are created inside the hook as an object.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using Custom Hook in the Component
&lt;/h2&gt;

&lt;p&gt;Inside the component, import the useFetch hook from its javascript file. After importing, call the hook with the API Url as an argument.&lt;/p&gt;

&lt;h3&gt;
  
  
  Fetching data using custom Hook
&lt;/h3&gt;

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

export function Home(){
    const {data,loading,error} = useFetch('https://localhost:4000')

        if(error){
           console.log(error)
        }

    return(
        {loading &amp;amp;&amp;amp; &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;}
        {data &amp;amp;&amp;amp; &amp;lt;div&amp;gt;{data.map(item =&amp;gt; &amp;lt;div&amp;gt;{item}&amp;lt;/div&amp;gt;)}&amp;lt;/div&amp;gt;}
    )
}


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

&lt;/div&gt;

&lt;p&gt;In addition to this, we can also customize the hook by making it return any function that can be called from the component.&lt;/p&gt;

&lt;p&gt;For example, we can create a refetch() function inside the hooks that re-fetches the API when called.&lt;/p&gt;

&lt;p&gt;This function can be returned from the hook and can be called from the component.&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
