<?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: Ananna Dristy</title>
    <description>The latest articles on DEV Community by Ananna Dristy (@dristy03).</description>
    <link>https://dev.to/dristy03</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%2F884355%2Fc7cf9aa7-3692-48a9-b3a6-36172dc3aabe.jpeg</url>
      <title>DEV Community: Ananna Dristy</title>
      <link>https://dev.to/dristy03</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dristy03"/>
    <language>en</language>
    <item>
      <title>Facing problem in starting Supabase on MacOs?</title>
      <dc:creator>Ananna Dristy</dc:creator>
      <pubDate>Thu, 29 Jun 2023 04:50:52 +0000</pubDate>
      <link>https://dev.to/dristy03/facing-problem-in-starting-supabase-on-macos-4al</link>
      <guid>https://dev.to/dristy03/facing-problem-in-starting-supabase-on-macos-4al</guid>
      <description>&lt;p&gt;Supabase is an open-source platform that provides a suite of tools and services to simplify the process of building and managing backend infrastructure for web and mobile applications. It combines the functionalities of a real-time database (PostgreSQL), authentication, and authorization system, and RESTful API generation.&lt;/p&gt;

&lt;p&gt;The Supabase CLI provides tools to develop the project locally and deploy to the Supabase Platform.&lt;br&gt;
To run Supabase locally, we use the commands:&lt;br&gt;
&lt;strong&gt;supabase init&lt;/strong&gt; &lt;br&gt;
&lt;strong&gt;supabase start&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The command &lt;strong&gt;supabase start&lt;/strong&gt; requires Docker Desktop to be running because it utilizes Docker to spin up a local instance of the Supabase server. Docker is a popular containerization platform that allows us to package applications and their dependencies into isolated container. &lt;/p&gt;

&lt;p&gt;When you give the command in the terminal specially in case of macos,&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;you may get an error even after you have your Docker Desktop running,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Error: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
  in github.com/supabase/cli/internal/utils.AssertDockerIsRunning:48
  in github.com/supabase/cli/internal/start.Run:39
Try rerunning the command with --debug to troubleshoot the error.

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

&lt;/div&gt;



&lt;p&gt;The solution of this problem is simple. Just don't get overwhelmed with the installation process. Install docker using homebrew.&lt;/p&gt;

&lt;p&gt;Steps are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Open a terminal on your macOS system.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Ensure that Homebrew is installed and up to date by running the following command:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
Once Homebrew is updated, you can proceed to install Docker by running the following command:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;brew install --cask docker
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
After the installation is complete, you can launch Docker by either searching for it in your Applications folder or by running the following command in the terminal:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;open /Applications/Docker.app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Docker will start up. &lt;/p&gt;

&lt;p&gt;Then, start giving all the supabase commands in your terminal:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
Initialize the Supabase login process:
&lt;/li&gt;
&lt;/ul&gt;

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Then you need to provide your access token by generating it from this &lt;a href="https://app.supabase.com/account/tokens"&gt;site&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Initialize a new Supabase project:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
Start the Supabase CLI:
&lt;/li&gt;
&lt;/ul&gt;

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

&lt;/div&gt;



&lt;p&gt;Then you may get the above error of &lt;em&gt;Cannot connect to the Docker daemon&lt;/em&gt;&lt;br&gt;
Just you need to add a command after that to set the path of docker.sock&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export DOCKER_HOST=unix://"$HOME/.docker/run/docker.sock"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And you will be good to go!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Bridge Between Lifecycle Methods &amp; Hooks</title>
      <dc:creator>Ananna Dristy</dc:creator>
      <pubDate>Sun, 23 Apr 2023 07:39:26 +0000</pubDate>
      <link>https://dev.to/dristy03/bridge-between-lifecycle-methods-hooks-54j7</link>
      <guid>https://dev.to/dristy03/bridge-between-lifecycle-methods-hooks-54j7</guid>
      <description>&lt;p&gt;React Hooks are more popular to us because of simplicity, performance, and scalability of functional components. For a better understanding of hooks, we gotta know the lifecycle of the react components. We will venture through the lifecycle of react component to reach our destination hooks. The lifecycle of a react component refers to a series of methods that are called in a specific order during the component's creation and update. There are three main phases in the lifecycle of a react component:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Mounting:&lt;/strong&gt; This phase happens when a component is first created and inserted into the DOM.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Updating:&lt;/strong&gt; This phase happens when a component's state or props change.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Unmounting:&lt;/strong&gt; This phase happens when a component is removed from the DOM.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;All these phases have some methods that allow us to control what happens at various points in the component's lifecycle. All these stuffs are technically belong to the class based components. We can't use these methods of lifecycle in functional components. Does this mean we can't have lifecycle in functional component? &lt;/p&gt;

&lt;p&gt;The answer is No. We can have lifecycle in functional components using certain hooks. In React 16.8, Hooks have been introduced. Now we can use abstracted versions of these lifecycle methods in functional component. But the question remains how was the versions of react before React 16.8? All the versions before React 16.8 had 2 types of components based on statefulness.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Class-based stateful component&lt;/li&gt;
&lt;li&gt;Stateless functional component&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Functional components in React were originally used only for rendering a view or UI elements. Prior to React 16.8, functional components were stateless and could not manage their own state. They were simply JavaScript functions that took in props and returned JSX elements. React Hooks were introduced in React 16.8 to bridge the gap between functional and class components, providing state management and lifecycle methods in functional components without the need for classes.&lt;/p&gt;

&lt;p&gt;There are a number of methods in each phases. If we jot it down together in a picture:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--PajqGGGb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m9od8ij4d248yaa74b1h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--PajqGGGb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m9od8ij4d248yaa74b1h.png" alt="lifecycle methods" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can write this down in the following way:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mounting: &lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;constructor()&lt;/li&gt;
&lt;li&gt;static getDerivedStateFromProps()&lt;/li&gt;
&lt;li&gt;render()&lt;/li&gt;
&lt;li&gt;componentDidMount()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Updating:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;static getDerivedStateFromProps()&lt;/li&gt;
&lt;li&gt;shouldComponentUpdate()&lt;/li&gt;
&lt;li&gt;render()&lt;/li&gt;
&lt;li&gt;getSnapshotBeforeUpdate()&lt;/li&gt;
&lt;li&gt;componentDidUpdate()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Unmounting:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;componentWillUnmount()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In addition to these methods, there are a few other methods that can be used to handle errors and update the state of the component.&lt;/p&gt;

&lt;p&gt;In order to handle all these methods in functional component, there are some equivalent lifecycle hooks. The built in react hooks are: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;useState():&lt;/strong&gt; add state to your functional components. It takes an initial state value as an argument and returns an array containing the current state and a function to update the state.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;useEffect():&lt;/strong&gt; perform side effects in the functional components. It takes takes two arguments: the first argument is a callback function that performs the side effect, and the second argument is an optional array of dependencies that tells react when the effect needs to be re-run.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;useContext():&lt;/strong&gt; access a React context in the functional components. It takes a context object as an argument and returns the current context value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;useRef():&lt;/strong&gt; create a ref in the functional components. It returns a mutable object with a current property that can be used to store any value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;useMemo():&lt;/strong&gt; memoize the result of a function so that it is not recalculated on every render. It takes two arguments: a function that returns a value, and an array of dependencies and returns the memoized value.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;useCallback():&lt;/strong&gt; same as useMemo hook but returns a memoized function instead of value.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;and many more.&lt;/p&gt;

&lt;p&gt;It's important to know that while React Hooks provide equivalent functionality to lifecycle methods, they often do so in a different way. This means that we may need to change our approach to writing components when using React Hooks instead of class components.&lt;/p&gt;

&lt;p&gt;The equivalence can be shown as:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lSslALEZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5my10pve8y2e7k2cjn0g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lSslALEZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5my10pve8y2e7k2cjn0g.png" alt="Equivalence" width="800" height="540"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Many other methods can be implemented using 2 hooks together; like getDerivedStateFromProps() can be achieved using useState() and useEffect(), getSnapshotBeforeUpdate() can be achieved using useState() and useLayoutEffect() and so on.&lt;/p&gt;




&lt;p&gt;Now we will walk through one by one.&lt;/p&gt;

&lt;h2&gt;
  
  
  UseState()
&lt;/h2&gt;

&lt;p&gt;State is a key concept in React which represents the internal data of a component. It can be changed over time by the component itself, either in response to user actions or other events. By updating the state of a component, the component can re-render itself and update its appearance or behavior based on the new data.&lt;/p&gt;

&lt;p&gt;First of all, we are gonna write a class based component that defines a stateful counter.&lt;br&gt;
&lt;/p&gt;

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

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };

    this.setCount = this.setCount.bind(this);
  }

  setCount() {
    this.setState((prevState) =&amp;gt; ({ count: prevState.count + 1 }));
  }

  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;button onClick={this.setCount}&amp;gt;Click me&amp;lt;/button&amp;gt;
        &amp;lt;p&amp;gt;Count: {this.state.count}&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export default App;



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

&lt;/div&gt;



&lt;p&gt;In this example, the component is defined using the class keyword and extends the React.component class provided by the React library. The component's state is initialized in the constructor method with a count property set to 0. The count state property is initialized to 0 in the component's constructor. The current value of count can be accessed using this.state.count in the render method.&lt;/p&gt;

&lt;p&gt;To update the state, we can use the setState method provided by React. For example, to increment the count property by 1, we would call this.setState({ count: this.state.count + 1 }) inside an event handler.&lt;/p&gt;

&lt;p&gt;The same thing is handled in functional component using useState hook.&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 [count, setCount] = useState(0);
  function handleClick() {
    setCount(prevCount =&amp;gt; prevCount + 1);  
}

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Click me&amp;lt;/button&amp;gt;
      &amp;lt;p&amp;gt;Count: {count}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;

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

&lt;/div&gt;



&lt;p&gt;In the previous class component example, state was managed using the component's constructor and setState method.&lt;br&gt;
In the functional component example, the useState hook is used to declare the count state variable and the setCount updater function. This hook simplifies state management by providing a convenient way to declare and update state in functional components.&lt;/p&gt;

&lt;p&gt;The useState hook takes an initial value as an argument and returns an array with two values: the current state value and the updater function. In the example, the initial value for count is 0.&lt;/p&gt;

&lt;p&gt;When the handleClick function is called, it updates the count state value by calling the setCount function with the new count value. This triggers a re-render of the component with the updated count value.&lt;/p&gt;
&lt;h2&gt;
  
  
  UseEffect()
&lt;/h2&gt;

&lt;p&gt;UseEffect hook replicates the behaviour of 3 methods of react lifecycle:  componentDidMount, componentDidUpdate and componentWillUnmount. First we are gonna look at the class based component.&lt;br&gt;
&lt;/p&gt;

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

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount() {
    console.log("Component mounted");
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.count !== prevState.count || this.props !== prevProps) {
      console.log("Component updated");
    }
  }

  componentWillUnmount() {
    console.log("Component unmounted");
  }

  handleClick() {
    this.setState((prevState) =&amp;gt; ({ count: prevState.count + 1 }));
  }

  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;button onClick={this.handleClick}&amp;gt;Click me&amp;lt;/button&amp;gt;
        &amp;lt;p&amp;gt;Count: {this.state.count}&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export default App;


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

&lt;/div&gt;



&lt;p&gt;In this example, the componentDidMount method runs when the component is mounted (i.e., after the first render). We log a message to the console to indicate that the component has mounted.&lt;/p&gt;

&lt;p&gt;The componentDidUpdate method runs whenever the component is updated. We check if the count state variable has changed from the previous state or if the props have changed since the previous props, and if either condition is true, we log a message to the console to indicate that the component has been updated.&lt;/p&gt;

&lt;p&gt;The componentWillUnmount method runs when the component is unmounted. We log a message to the console to indicate that the component has been unmounted.&lt;/p&gt;

&lt;p&gt;Finally, we have a handleClick function that updates the count state variable when the button is clicked. This triggers a re-render of the component, which causes the componentDidUpdate method to run if the count state variable has changed.&lt;/p&gt;

&lt;p&gt;Now, in order to achieve this same behaviour as class based component, we will be using useEffect hook in functional component.&lt;br&gt;
&lt;/p&gt;

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

function App() {
  const [count, setCount] = useState(0);

  useEffect(() =&amp;gt; {
    console.log("Component mounted");

    return () =&amp;gt; {
      console.log("Component unmounted");
    };
  }, []);

  useEffect(() =&amp;gt; {
    console.log("Count updated");
  }, [count]);

  function handleClick() {
    setCount((prevCount) =&amp;gt; prevCount + 1);
  }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Click me&amp;lt;/button&amp;gt;
      &amp;lt;p&amp;gt;Count: {count}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;


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

&lt;/div&gt;



&lt;p&gt;In this example, we're using two useEffect hooks to replicate the behavior of the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods.&lt;/p&gt;

&lt;p&gt;The first useEffect hook runs when the component is mounted (i.e., after the first render). We log a message to the console to indicate that the component has mounted. This useEffect hook also returns a function that will be called when the component is unmounted. In this case, we're logging a message to the console to indicate that the component has been unmounted. The empty dependency array [] ensures that this effect only runs once, when the component mounts.&lt;/p&gt;

&lt;p&gt;The second useEffect hook runs whenever the count state variable changes (i.e., after each update). We log a message to the console to indicate that the count has been updated. The count dependency array [count] ensures that this effect only runs when the count state variable changes.&lt;/p&gt;

&lt;p&gt;Finally, we have a handleClick function that updates the count state variable when the button is clicked. This triggers a re-render of the component, which causes the second useEffect hook to run if the count state variable has changed.&lt;/p&gt;

&lt;h2&gt;
  
  
  UseMemo()
&lt;/h2&gt;

&lt;p&gt;UseMemo hook works like shouldComponentUpdate() method which is mainly used to memorize a value so that it doesn't run in every render. The following shows a example using shouldComponentUpdate() in class based component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count1: 0,
      count2: 0,
      expensiveValue: this.expensiveCalculation(0)
    };
    this.handleClick1 = this.handleClick1.bind(this);
    this.handleClick2 = this.handleClick2.bind(this);
    this.expensiveCalculation = this.expensiveCalculation.bind(this);
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      nextState.count1 !== this.state.count1 ||
      nextState.count2 !== this.state.count2
    );
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.count1 !== this.state.count1) {
      this.setState({
        expensiveValue: this.expensiveCalculation(this.state.count1)
      });
    }
  }

  handleClick1() {
    this.setState((prevState) =&amp;gt; ({
      count1: prevState.count1 + 1
    }));
  }

  handleClick2() {
    this.setState((prevState) =&amp;gt; ({
      count2: prevState.count2 + 1
    }));
  }

  expensiveCalculation(num) {
    console.log("Calculating...");
    for (let i = 0; i &amp;lt; 1000000000; i++) {
      num += 1;
    }
    return num;
  }

  render() {
    const { count1, count2, expensiveValue } = this.state;
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;div&amp;gt;
          &amp;lt;h2&amp;gt;Counter 1: {count1}&amp;lt;/h2&amp;gt;
          &amp;lt;button onClick={this.handleClick1}&amp;gt;Add Me&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div&amp;gt;
          &amp;lt;h2&amp;gt;Counter 2: {count2}&amp;lt;/h2&amp;gt;
          &amp;lt;button onClick={this.handleClick2}&amp;gt;Add Me&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div&amp;gt;
          &amp;lt;h2&amp;gt;Expensive Value:&amp;lt;/h2&amp;gt;
          {expensiveValue}
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

export default App;

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

&lt;/div&gt;



&lt;p&gt;In this example, the expensiveCalculation function performs a time-consuming calculation, simulating a case where the value is difficult to calculate and requires significant resources. So, we're using the shouldComponentUpdate method to optimize rendering, and only re-calculating the expensive value when the count1 state changes.&lt;/p&gt;

&lt;p&gt;The shouldComponentUpdate method compares the current count1 state with the next count1 state, and only allows the function expensiveCalculation to run if they are different. This avoids unnecessary calculating when the count1 state has not changed.&lt;/p&gt;

&lt;p&gt;We're also using componentDidUpdate lifecycle methods to perform the expensive calculation and update the state accordingly. We only perform this calculation when the count1 state changes.&lt;/p&gt;

&lt;p&gt;Same optimization is done using useMemo hook. The following shows the transformed version into functional component:&lt;br&gt;
&lt;/p&gt;

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

function App() {
  const [count1, setCount1] = useState(0);
  const [count2, setCount2] = useState(0);
  const expensiveValue = useMemo(() =&amp;gt; expensiveCalculation(count1), [count1]);

  function handleClick1() {
    setCount1((prevCount) =&amp;gt; prevCount + 1);
  }

  function handleClick2() {
    setCount2((prevCount) =&amp;gt; prevCount + 1);
  }

  function expensiveCalculation(num) {
    console.log("Calculating...");
    for (let i = 0; i &amp;lt; 1000000000; i++) {
      num += 1;
    }
    return num;
  }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;h2&amp;gt;Counter 1: {count1}&amp;lt;/h2&amp;gt;
        &amp;lt;button onClick={handleClick1}&amp;gt;Add Me&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;h2&amp;gt;Counter 2: {count2}&amp;lt;/h2&amp;gt;
        &amp;lt;button onClick={handleClick2}&amp;gt;Add Me&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;h2&amp;gt;Expensive Value:&amp;lt;/h2&amp;gt;
{expensiveValue}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;

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

&lt;/div&gt;



&lt;p&gt;Here, the useMemo hook is used to calculate the expensiveCalculation only when count1 changes. It takes two arguments: a function that returns the value to be memoized (in this case, the expensiveCalculation function) and an array of dependencies (in this case, [count1]). Whenever count1 changes, the function expensiveCalculation is re-executed and the is expensiveValue updated.&lt;/p&gt;

&lt;p&gt;This means that if the count1 state hasn't changed, the cached result of expensiveCalculation will be used instead of recalculating it.&lt;/p&gt;

&lt;p&gt;We can see the same effect of optimization in the console log. The expensiveCalculation function is only recalculated when the count state changes, and is not recalculated when the component re-renders due to other state changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In this way all other hooks somehow replicate the methods of the lifecycle that are prevailed in class based components fulfilling all three phases. The introduction of hooks has eliminated a lot of verbosity in a class-based component and made the code easier and simpler to write and read.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>hooks</category>
      <category>lifecycle</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Using UseEffect Hook: Avoiding Excessive Re-rendering</title>
      <dc:creator>Ananna Dristy</dc:creator>
      <pubDate>Wed, 19 Apr 2023 11:23:25 +0000</pubDate>
      <link>https://dev.to/dristy03/using-useeffect-hook-avoiding-excessive-re-rendering-3khm</link>
      <guid>https://dev.to/dristy03/using-useeffect-hook-avoiding-excessive-re-rendering-3khm</guid>
      <description>&lt;p&gt;React is one of the most popular front-end web development frameworks and has gained widespread adoption since its release in 2013. In React, there are two ways to define a component: class components and functional components. Functional components are widely used now-a-days because they are simpler and more lightweight than class components. To manage states and side effects, hooks are used in functional component which have made our works much easier.&lt;/p&gt;

&lt;p&gt;UseEffect is one of the react hooks that allows functional components to perform side effects, such as fetching data or updating the DOM, in response to changes in state or props. But for the beginners, it may be somewhat troublesome. There are some common mistakes while using useEffect in code.&lt;/p&gt;

&lt;p&gt;I have assumed that people reading this blog have already used useEffect hooks before. One of the simplest examples for showing useEffect hook is of increasing counter value and displaying the value in the webpage.&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";

function App() {
  const [count, setCount] = useState(0)

  useEffect(()=&amp;gt;
  {
    console.log("Rerendering!")

    setInterval(() =&amp;gt; {
      setCount(count+1)
    },1000)
  },[count])

  return (
  &amp;lt;div&amp;gt;Current count is: {count}&amp;lt;/div&amp;gt;
  )
}

export default App;



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

&lt;/div&gt;

&lt;p&gt;We have used the &lt;strong&gt;useState&lt;/strong&gt; hook to define a state variable called &lt;strong&gt;count&lt;/strong&gt; and a function called &lt;strong&gt;setCount&lt;/strong&gt; which will be used to update the state of count. In this case, the initial value of count is set to 0.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;useEffect&lt;/strong&gt; hook is used to handle side effects in functional components. In this case, it sets an interval using &lt;strong&gt;setInterval&lt;/strong&gt; to update the &lt;strong&gt;count&lt;/strong&gt; value every 1000ms (1 second). Whenever the &lt;strong&gt;count&lt;/strong&gt; value changes, the &lt;strong&gt;useEffect&lt;/strong&gt; hook is called again due to the dependency array &lt;strong&gt;[count]&lt;/strong&gt;, and the component is re-rendered.&lt;/p&gt;

&lt;p&gt;You can find the running code &lt;a href="https://codesandbox.io/s/react-useeffect-ex-1-h9fhrd" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;After running the code, you will observe some abnormalities in the webpage. You will understand better if you open your console. It have been rendering infinitely. This has happened because the count is updating every second. Since the count is the dependency in our useEffect, it runs the function again and again. &lt;/p&gt;

&lt;p&gt;But a question can appear in your mind, why the number of Rendering printed on the console is more than the count. As we already know the function is run when the &lt;strong&gt;count&lt;/strong&gt; is changed. This happens because the &lt;strong&gt;setInterval&lt;/strong&gt; function is asynchronous, it is possible for multiple updates to be scheduled before the component has a chance to re-render. This means that there may be several updates to the count state variable before the component actually re-renders and displays the updated count. This is why you may see more log messages for "Rendering!" than the count updates you observe.&lt;/p&gt;

&lt;p&gt;Now, to remove this infinite loop, we will now update the code a bit.&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";

function App() {
  const [count, setCount] = useState(0);

  useEffect(() =&amp;gt; {
    console.log("Rerendering!");

    setInterval(() =&amp;gt; {
      setCount((prev) =&amp;gt; prev + 1);
    }, 1000);
  }, []);

  return &amp;lt;div&amp;gt;Current count is: {count}&amp;lt;/div&amp;gt;;
}

export default App;



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

&lt;/div&gt;

&lt;p&gt;Here, we pass an empty dependency array &lt;strong&gt;[]&lt;/strong&gt; to the &lt;strong&gt;useEffect&lt;/strong&gt; hook, which means that the effect will only run once on mount and not re-run on updates. We also use a &lt;strong&gt;functional update&lt;/strong&gt; to update the count state variable inside the &lt;strong&gt;setInterval&lt;/strong&gt; function, which ensures that we always have the latest value of count and avoids the infinite loop.&lt;br&gt;
You can see the running code &lt;a href="https://codesandbox.io/s/jolly-cache-2dlbrq?file=/src/App.js" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This time the code runs almost perfectly. The re-rendering is seen on the log once or twice. It's supposed to be one. But because your &lt;strong&gt;App&lt;/strong&gt; is wrapped inside &lt;strong&gt;React.StrictMode&lt;/strong&gt;, it renders twice. &lt;strong&gt;StrictMode&lt;/strong&gt; renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful). So, you may get 2 log messages of Rerendering!&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%2Fw7el3rhgtunewfuqof6t.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%2Fw7el3rhgtunewfuqof6t.png" alt="index.js"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, it is the time for making this piece of code perfect as we have said the previous one was almost perfect. The best practice of using useEffect is with a cleanup function.&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";

function App() {
  const [count, setCount] = useState(0);

  useEffect(() =&amp;gt; {
    console.log("Rerendering!");

    const interval = setInterval(() =&amp;gt; {
      setCount((prev) =&amp;gt; prev + 1);
    }, 1000);

    return () =&amp;gt; {
      clearInterval(interval);
    };
  }, []);

  return &amp;lt;div&amp;gt;Current count is: {count}&amp;lt;/div&amp;gt;;
}

export default App;



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

&lt;/div&gt;

&lt;p&gt;In this code, the &lt;strong&gt;clearInterval&lt;/strong&gt; function is called inside the &lt;strong&gt;cleanup&lt;/strong&gt; function that is returned from the &lt;strong&gt;useEffect&lt;/strong&gt; hook. You can find the running code &lt;a href="https://codesandbox.io/s/beautiful-mcclintock-sd8u5v?file=/src/App.js:24-426" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;useEffect&lt;/strong&gt; hook sets an interval using the &lt;strong&gt;setInterval&lt;/strong&gt; function, which repeatedly updates the &lt;strong&gt;count&lt;/strong&gt; state variable. Without a &lt;strong&gt;cleanup&lt;/strong&gt; function, the interval would continue running even after the component is unmounted, leading to potential memory leaks and performance issues. The &lt;strong&gt;cleanup&lt;/strong&gt; function ensures that the interval is cleared when the component is unmounted or when the count state variable changes and the effect is re-run.&lt;/p&gt;

&lt;p&gt;Hope that now you all can write useEffect hooks without any confusion of excessive re-rendering. This is all for now. For any enquiries, let me know. &lt;/p&gt;

</description>
      <category>react</category>
      <category>hooks</category>
      <category>useeffect</category>
    </item>
    <item>
      <title>Hasura Custom Authentication Using JWT</title>
      <dc:creator>Ananna Dristy</dc:creator>
      <pubDate>Wed, 29 Jun 2022 15:31:05 +0000</pubDate>
      <link>https://dev.to/dristy03/hasura-custom-authentication-using-jwt-cik</link>
      <guid>https://dev.to/dristy03/hasura-custom-authentication-using-jwt-cik</guid>
      <description>&lt;p&gt;Hasura, as in Hasura GraphQL engine is a very popular web application that helps in building API's 10 times faster than before. It has built in authorization and caching; and gives instant realtime GraphQL APIs on a Postgres database.&lt;/p&gt;

&lt;p&gt;Hasura supports two modes of authentication configuration.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Using webhook&lt;/li&gt;
&lt;li&gt;Using JWT token&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Today I will be talking about authentication using JWT. Before that lets talk about JWT.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;JWT means JSON Web Token. It is mainly used to identify an authenticated user and share information between two parties, like client and server. It contains a JSON object which bears public information but only can be verified by the signer who originally created the token by a secret key.&lt;/p&gt;

&lt;p&gt;JWT has mainly 3 parts:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Header:&lt;/strong&gt; &lt;br&gt;
It contains the signing algorithm such as SHA256, RSA and the type of the token which is JWT&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "alg": "HS256",
    "typ": "JWT"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Payload:&lt;/strong&gt;&lt;br&gt;
It contains the claims and the data to be shared. Claims are statements about an entity (i.e user).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Signature:&lt;/strong&gt;&lt;br&gt;
It is generated by the using the algorithm mentioned in the header in encoded header, encoded payload and a secret key together. It is used to verify the information wasn't changed along the way and the authenticity of the sender by the secret key.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  your-256-bit-secret

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

&lt;/div&gt;



&lt;p&gt;Putting all these 3 parts together a token is formed.&lt;br&gt;
&lt;/p&gt;

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

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

&lt;/div&gt;



&lt;p&gt;When a user is signed up or logged in, a JWT is returned; which is used to access private routes in a server. In order to access private routes, the client should send the JWT, typically in the Authorization header using the Bearer schema. The server's protected routes will check for a valid JWT in the Authorization header. If the JWT is decoded and verified, the user will be allowed to access protected routes.&lt;/p&gt;




&lt;p&gt;The GraphQL engine is configured to use JWT authorization mode to authorize all incoming requests to the Hasura GraphQL engine server. Hasura docs is self sufficient enough to explain the flow of JWT. It has provide a flow diagram:&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%2F50v4mx7h3kxpn0kw7gj1.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%2F50v4mx7h3kxpn0kw7gj1.png" alt="courtesy - hasura.io"&gt;&lt;/a&gt;&lt;br&gt;
&lt;sup&gt;courtesy - hasura.io&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;Before using JWT mode, the GraphQL end point has to be secured using admin secret. Otherwise JWT won't be effective. In order to secure the endpoint, &lt;strong&gt;HASURA_GRAPHQL_ADMIN_SECRET&lt;/strong&gt; has to be added on the config vars.&lt;/p&gt;

&lt;p&gt;After that, you need to pass HASURA_GRAPHQL_JWT_SECRET on the environment variable. The format would be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
 "type": "&amp;lt;standard-JWT-algorithms&amp;gt;",
 "key": "&amp;lt;optional-key-as-string&amp;gt;"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;where- &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Type:&lt;/strong&gt; Standard JWT algorithms - Hasura supports HS256, HS384, HS512, RS256, RS384, RS512, Ed25519 &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key:&lt;/strong&gt; The secret key used to decode and encode the JWT.&lt;br&gt;
JWT contains several parts. The data one needed to send and the custom claims as mentioned above. By default Hasura engine looks under "&lt;a href="https://hasura.io/jwt/claims" rel="noopener noreferrer"&gt;https://hasura.io/jwt/claims&lt;/a&gt;". 2 things are mandatory to be present in the custom claims:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;x-hasura-default-role field:&lt;/strong&gt; default role of the user&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;x-hasura-allowed-roles field:&lt;/strong&gt; an array of allowed roles for the user&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The claims in the JWT can have other x-hasura-* fields where their values can only be strings.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true,
  "iat": 1516239022,
  "https://hasura.io/jwt/claims": {
    "x-hasura-allowed-roles": ["editor", "user", "mod"],
    "x-hasura-default-role": "user",
    "x-hasura-user-id": "1234567890",
    "x-hasura-org-id": "123",
    "x-hasura-custom": "custom-value"
  }
}

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

&lt;/div&gt;



&lt;p&gt;Now the JWT should be sent by the client to the Hasura GraphQL engine via the &lt;strong&gt;Authorization: Bearer  header&lt;/strong&gt;.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;One can find many blogs on authentication by JWT using Auth0 or firebase and many more. But there are less resources of doing custom authentication without using any auth server. I am going to lay out the procedure step by step.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We are going to use &lt;strong&gt;Next.JS&lt;/strong&gt; which is a frontend framework in that it is ReactJS, React-DOM with a NextJS development server for server-side rendering so that we wont need separate backend framework. For GraphQL client, we are going to use &lt;strong&gt;urql&lt;/strong&gt;. You can learn more about urql here.&lt;/p&gt;

&lt;p&gt;Before going to the coding part, we need to setup our hasura console. We will run our hasura graphql engine on heroku. We need to visit this page and press on the button : Deploy to Heroku. And deploy our app. Now we can find our container in Hasura. We can open our console from there. &lt;/p&gt;

&lt;p&gt;In our console, we will create a schema first i.e our database. Then we will create all the tables we need. For authentication, we need a user table containing email, password, id. If you want you can add any number of columns. Then we have to set permission of the tables as per need.&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%2Fv4x05nd9ks0ppq22i3rf.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%2Fv4x05nd9ks0ppq22i3rf.png" alt="Permissions"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  SignUp
&lt;/h2&gt;

&lt;p&gt;We basically do mutation for signing up. In hasura, we make this graphql mutation code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mutation($email: String!, $password: String!) {
    insert_users_one(object: {
        email: $email,
        password: $password
    }) {
        id
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It means, we need to pass &lt;strong&gt;email&lt;/strong&gt; and &lt;strong&gt;password&lt;/strong&gt; to the insert_users_one; which will insert the user on the users table and return us the &lt;strong&gt;id&lt;/strong&gt; of that user.&lt;/p&gt;

&lt;p&gt;This mutation has to be done on the backend. So we need to use urql/core package for Node.js. To learn about the core and node.js usage, visit here.&lt;/p&gt;

&lt;p&gt;We need to first install some packages.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @urql/core graphql
or
yarn add @urql/core graphql
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we have to create a graphql client file anywhere for setting up the client. Lets say we have named it gql-client.js and contents of the file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createClient } from "@urql/core";

const client = createClient({
    url: "your_graphql_post_url",
    fetchOptions: {
        headers: {
            "content-type": "application/json",
            "x-hasura-admin-secret": "your_admin_secret",
        },
    },
});
export default client;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your url part will the url present here-&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%2Fel5y0jectj4mk9lw7ntq.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%2Fel5y0jectj4mk9lw7ntq.png" alt="url"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;x-hasura-admin-secret will be the &lt;strong&gt;HASURA_GRAPHQL_ADMIN_SECRET&lt;/strong&gt; you have added in the environment vars in order to secure the endpoint.&lt;/p&gt;




&lt;p&gt;Next we will create a file under api on the pages folder which will work as our api for signing up.&lt;/p&gt;

&lt;p&gt;As we are doing authentication using jwt, we need to generate the token. First we need to set our data we want to send and the claims.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const tokenContents = {
    sub: "id that we will get from mutation",
    "https://hasura.io/jwt/claims": {
        "x-hasura-allowed-roles": ["user"],
        "x-hasura-default-role": "user",
        "x-hasura-user-id": "id that we will get from mutation",
    },
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also add email in the content or can send and anything with x-hasura prefix under claims.&lt;/p&gt;

&lt;p&gt;Then we need to produce the token by passing the contents and the key that we added in &lt;strong&gt;HASURA_GRAPHQL_JWT_SECRET&lt;/strong&gt;. For that we will be using the jsowebtoken package. We need to install it first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install jsonwebtoken
or
yarn add jsonwebtoken
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we have to use the sign method from jsonwebtoken.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const token = jsonwebtoken.sign(tokenContents, "your_jwt_secret_key");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is not a good idea to keep password of the users in the table. It is certainly a breach in privacy. So, we will hash the password using bcrypt hashing function&lt;br&gt;
We need to install the package.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install bcryptjs
or
yarn add bcryptjs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to learn more about bcrypt, check here. We will generate a salt ( a random string that makes the hash unpredictable) and hash that password using the salt.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We need to import client from gql-client.js to use the client for mutation. Then call the mutation function from the client and get our id from the handler.&lt;/p&gt;

&lt;p&gt;Here's the full 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 jsonwebtoken from "jsonwebtoken";
import bcrypt from "bcryptjs";
import client from "your_gql-client_file_path";

const SIGNUP = `
mutation($email: String!, $password: String!) {
insert_users_one(object:
{email: $email, password: $password}){
id}}`;

const generateToken = (id) =&amp;gt; {
    const tokenContents = {
        sub: id,
        "https://hasura.io/jwt/claims": {
            "x-hasura-allowed-roles": ["user"],
            "x-hasura-default-role": "user",
            "x-hasura-user-id": id,
        },
    };
    return jsonwebtoken.sign(tokenContents, "your_jwt_secret_key");
};

const handler = async (req, res) =&amp;gt; {
    const { email, password } = req.body;

    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    client
        .mutation(SIGNUP, { email: email, password: hashedPassword })
        .toPromise()
        .then((result) =&amp;gt; {
            if (result.error) {
                return res.status(400).json({
                    message: result.error.message,
                });
            } else {
                return res.status(200).json({
                    data: result.data,
                    token: generateToken(
                        result.data.insert_users_one.id.toString()
                    ),
                });
            }
        });
};

export default handler;

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Login
&lt;/h2&gt;

&lt;p&gt;Login is much easier than signup. All we need to do is to make a query graphql code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;query($email: String!) {
    users(where: {
        email: {
            _eq: $email
        }
    }) {
        id,
        password
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we will match the email and return the id and password of the user. Next we will match the hashing the password using bcrypt. For that we are going to use bcrypt.compare function.&lt;/p&gt;

&lt;p&gt;The full code is :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import jsonwebtoken from "jsonwebtoken";
import bcrypt from "bcryptjs";
import client from "your_gql-client_file_path";

const LOGIN = `
query($email: String!) {
users(where: {email: {_eq: $email}}) {
id,
password
}}`;

const generateToken = (id) =&amp;gt; {
    const tokenContents = {
        sub: id,
        "https://hasura.io/jwt/claims": {
            "x-hasura-allowed-roles": ["user"],
            "x-hasura-default-role": "user",
            "x-hasura-user-id": id,
        },
    };

    return jsonwebtoken.sign(tokenContents, "your_jwt_secret_key");
};

const handler = async (req, res) =&amp;gt; {
    const { email, password } = req.body;

    const result = await client.query(LOGIN, { email: email }).toPromise();

    if (result.error) {
        res.status(400).json({
            message: result.error.message,
        });
    }
    if (
        result.data.users.length == 1 &amp;amp;&amp;amp;
        (await bcrypt.compare(password, result.data.users[0].password))
    ) {
        return res.status(200).json({
            data: result.data,
            token: generateToken(result.data.users[0].id),
        });
    } else {
        return res.status(200).json({ message: "Invalid Credentials" });
    }
};

export default handler;

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

&lt;/div&gt;






&lt;p&gt;Now just calling these two api from the frontend, we are good to go. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Congrats! Now you can implement authentication without using any auth services.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>hasura</category>
      <category>urql</category>
      <category>authentication</category>
      <category>jwt</category>
    </item>
  </channel>
</rss>
