<?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: Mohamed Ajmal P</title>
    <description>The latest articles on Forem by Mohamed Ajmal P (@ajmalp5).</description>
    <link>https://forem.com/ajmalp5</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%2F870250%2F945030e9-1b12-46d0-b815-86441bf1d4c6.jpg</url>
      <title>Forem: Mohamed Ajmal P</title>
      <link>https://forem.com/ajmalp5</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/ajmalp5"/>
    <language>en</language>
    <item>
      <title>Django QuerySet API (Detailed Explain)</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Sat, 28 Jan 2023 18:29:37 +0000</pubDate>
      <link>https://forem.com/ajmalp5/django-queryset-api-2hch</link>
      <guid>https://forem.com/ajmalp5/django-queryset-api-2hch</guid>
      <description>&lt;p&gt;In Django, a QuerySet is a collection of objects from a database model. It can be used to retrieve, update, and delete records from the database. The QuerySet API provides a set of methods for working with the data.&lt;/p&gt;

&lt;p&gt;Some common methods of the QuerySet API include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;filter(): filters the queryset based on the provided keyword arguments&lt;/li&gt;
&lt;li&gt;exclude(): filters the queryset to exclude items that match the provided keyword arguments&lt;/li&gt;
&lt;li&gt;all(): returns all objects in the queryset&lt;/li&gt;
&lt;li&gt;get(): retrieves a single object that matches the provided keyword arguments, or raises an exception if no match is found&lt;/li&gt;
&lt;li&gt;create(): creates a new object and saves it to the database&lt;/li&gt;
&lt;li&gt;update(): updates one or more fields on all objects in the queryset&lt;/li&gt;
&lt;li&gt;delete(): deletes all objects in the queryset&lt;/li&gt;
&lt;li&gt;first(): returns the first object in the queryset&lt;/li&gt;
&lt;li&gt;last(): returns the last object in the queryset&lt;/li&gt;
&lt;li&gt;count(): returns the number of objects in the queryset&lt;/li&gt;
&lt;li&gt;exists(): returns a Boolean indicating if the queryset contains any objects.
You can chain these methods together to create more complex queries.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;&lt;strong&gt;filter()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Django, the filter() method of a QuerySet is used to filter the queryset based on the provided keyword arguments. The resulting queryset will contain only the objects that match the specified filters.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the filter() method to retrieve all objects from a database model where the published field is True:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# Retrieve all objects from the MyModel where the published field is True
queryset = MyModel.objects.filter(published=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can chain multiple filters together by chaining multiple filter() methods, 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;queryset = MyModel.objects.filter(published=True).filter(author='John Smith')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will return all objects from the MyModel where the published field is True and the author field is John Smith.&lt;/p&gt;

&lt;p&gt;You can also use the Q object to create more complex queries using OR or AND statements 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;from django.db.models import Q

queryset = MyModel.objects.filter(Q(published=True) | Q(author='John Smith'))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will return all objects from the MyModel where the published field is True or the author field is John Smith&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;exclude()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Django, the exclude() method of a QuerySet is used to exclude objects from the queryset that match the provided keyword arguments. The resulting queryset will contain only the objects that do not match the specified filters.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the exclude() method to retrieve all objects from a database model where the published field is False:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# Retrieve all objects from the MyModel where the published field is False
queryset = MyModel.objects.exclude(published=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can chain multiple exclude() methods together to exclude multiple conditions, 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;queryset = MyModel.objects.exclude(published=True).exclude(author='John Smith')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will return all objects from the MyModel where the published field is False and the author field is not John Smith.&lt;/p&gt;

&lt;p&gt;You can also use the Q object to create more complex queries using OR or AND statements 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;from django.db.models import Q

queryset = MyModel.objects.exclude(Q(published=True) | Q(author='John Smith'))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will return all objects from the MyModel where the 'published' field is False or the 'author' field is not 'John Smith'&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;all()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Django, the all() method of a QuerySet is used to retrieve all objects from a database model. It returns a queryset containing all objects in the database table that corresponds to the model.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# Retrieve all objects from the MyModel
queryset = MyModel.objects.all()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method does not take any arguments, and it is often the starting point for creating more complex queries using other QuerySet methods such as filter(), exclude(), order_by(), limit(), etc.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can chain multiple QuerySet methods to retrieve all objects from a database model where the published field is True and order them by date_published:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;queryset = MyModel.objects.filter(published=True).order_by('-date_published')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;get()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Django, the get() method of a QuerySet is used to retrieve a single object from a database model that matches the provided keyword arguments. The method will raise a DoesNotExist exception if no matching object is found, and a MultipleObjectsReturned exception if multiple objects are found.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the get() method to retrieve an object from a database model where the id field is 1:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# Retrieve an object from the MyModel where the id field is 1
obj = MyModel.objects.get(id=1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also use the get() method to retrieve an object by its primary key, which is the default field named id:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;obj = MyModel.objects.get(pk=1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also use the get() method to retrieve an object by other fields, 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;obj = MyModel.objects.get(name='John Smith')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's important to note that you should use the get() method only if you know that the query will return only one object. If your query might return multiple objects, you should use filter() instead, which will return a queryset containing all matching objects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;create()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Django, the create() method of a Manager (the default manager of a model) is used to create a new object and save it to the database in one step. It's similar to instantiating a model object, setting its properties, and then calling save() on it.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the create() method to create a new object of a model and save it to the database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# create a new object of MyModel and save it to the database
obj = MyModel.objects.create(name='John Smith', age=30)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The create() method takes keyword arguments that correspond to the fields of the model, and it returns the new object that has been saved to the database.&lt;/p&gt;

&lt;p&gt;The create() method also accepts a defaults parameter which is a dictionary containing default values for fields that aren't specified in the keyword arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;obj = MyModel.objects.create(name='Jane Smith', defaults={'age':25})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create an object of the model with name='Jane Smith' and age=25 and will save it to the database.&lt;/p&gt;

&lt;p&gt;Please note that the create() method will raise a IntegrityError exception if the object could not be saved due to a violation of a database constraint, such as a unique constraint.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;update()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Django, the update() method of a QuerySet is used to update multiple objects in the database at once. It updates the fields of the objects that match the provided keyword arguments.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the update() method to update all objects in the MyModel table where the published field is False and set it to True:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# update the 'published' field of all objects in the MyModel table where the published field is False
MyModel.objects.filter(published=False).update(published=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The update() method takes keyword arguments that correspond to the fields of the model, and it updates the fields of all objects that match the provided keyword arguments.&lt;/p&gt;

&lt;p&gt;You can also use the update() method to update fields of the object by mathematical operations, 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;MyModel.objects.filter(published=True).update(views=F('views')+1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will increment the views field of all objects in the MyModel table where the published field is True.&lt;/p&gt;

&lt;p&gt;Please note that the update() method doesn't call the save() method on the objects, so any custom logic you have in the save() method will not be executed when using update(). Also the update() method doesn't call the pre_save or post_save signals, so if you're depending on these signals, you should use the save() method instead.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;delete()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Django, the delete() method of a QuerySet is used to delete multiple objects from the database at once. It deletes all objects that match the provided keyword arguments.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the delete() method to delete all objects in the MyModel table where the published field is False:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# delete all objects in the MyModel table where the published field is False
MyModel.objects.filter(published=False).delete()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also use the delete() method on a single object, 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;obj = MyModel.objects.get(pk=1)
obj.delete()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note that the delete() method doesn't call the delete() method on the objects, so any custom logic you have in the delete() method will not be executed when using delete(). Also the delete() method doesn't call the pre_delete or post_delete signals, so if you're depending on these signals, you should use the delete() method on the object instead.&lt;/p&gt;

&lt;p&gt;Also the delete() method will raise a ProtectedError if you're trying to delete an object that is related to another object and the related object has protect=True on the foreign key, 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;class Parent(models.Model):
    name = models.CharField(max_length=32)

class Child(models.Model):
    name = models.CharField(max_length=32)
    parent = models.ForeignKey(Parent, on_delete=models.PROTECT)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, if you try to delete a Parent object that has related Child objects, it will raise a ProtectedError&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;first()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Django, the first() method of a QuerySet is used to retrieve the first object that matches the provided filters.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the first() method to retrieve the first object in the MyModel table where the published field is True:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# retrieve the first object in the MyModel table where the published field is True
first_obj = MyModel.objects.filter(published=True).first()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first() method returns the first object that matches the filters, or None if no matching object is found. If you are trying to retrieve the first object and you are not sure whether the queryset will return any results or not, you can use the first() method and check if it returns None or not.&lt;/p&gt;

&lt;p&gt;You can also use the first() method with no parameters and it will return the first object in the table, 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;first_obj = MyModel.objects.first()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note that the first() method is equivalent to [queryset.all()[0]] or [queryset[0]] but is more readable and can be more efficient with large querysets because it stops querying the database as soon as it finds the first result.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;last()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;matches the provided filters. The last() method works similarly to the first() method, but instead of returning the first object, it returns the last object.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the last() method to retrieve the last object in the MyModel table where the published field is True:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# retrieve the last object in the MyModel table where the published field is True
last_obj = MyModel.objects.filter(published=True).last()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The last() method returns the last object that matches the filters, or None if no matching object is found. If you are trying to retrieve the last object and you are not sure whether the queryset will return any results or not, you can use the last() method and check if it returns None or not.&lt;/p&gt;

&lt;p&gt;You can also use the last() method with no parameters and it will return the last object in the table, 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;last_obj = MyModel.objects.last()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note that the last() method is equivalent to [queryset.all()[-1]] or [queryset[-1]] but is more readable and can be more efficient with large querysets because it stops querying the database as soon as it finds the last result.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;count()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Django, the count() method of a QuerySet is used to retrieve the number of objects that match the provided filters.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the count() method to retrieve the number of objects in the MyModel table where the published field is True:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# retrieve the count of objects in the MyModel table where the published field is True
count = MyModel.objects.filter(published=True).count()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The count() method returns an integer representing the number of objects that match the filters.&lt;/p&gt;

&lt;p&gt;You can also use the count() method with no parameters and it will return the count of all objects in the table, 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;count = MyModel.objects.count()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note that the count() method is more efficient than loading all objects into memory and then counting them using Python's len() function, especially when working with large datasets. Also, it may be more efficient than using SQL COUNT() function, because it will use COUNT(*) and stop querying as soon as the count is known.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;exists()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Django, the exists() method of a QuerySet is used to check if any object exists in the database that matches the provided filters.&lt;/p&gt;

&lt;p&gt;Here is an example of how you can use the exists() method to check if any objects exist in the MyModel table where the published field is True:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from myapp.models import MyModel

# check if any objects exist in the MyModel table where the published field is True
exists = MyModel.objects.filter(published=True).exists()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The exists() method returns a Boolean indicating whether any objects exist that match the filters. It returns True if any objects exist and False if no objects exist.&lt;/p&gt;

&lt;p&gt;You can also use the exists() method with no parameters and it will return True if there are any objects in the table, 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;exists = MyModel.objects.exists()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note that the exists() method is more efficient than loading all objects into memory and then checking if the queryset is empty, especially when working with large datasets. Also, it may be more efficient than using SQL EXISTS() function, because it will use LIMIT 1 and stop querying as soon as the first object is found.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In conclusion, the QuerySet API in Django is a powerful tool that allows you to retrieve, create, update and delete objects in a database. The QuerySet API provides several methods such as &lt;em&gt;filter()&lt;/em&gt;, &lt;em&gt;exclude()&lt;/em&gt;, &lt;em&gt;all()&lt;/em&gt;, &lt;em&gt;get()&lt;/em&gt;, &lt;em&gt;create()&lt;/em&gt;, &lt;em&gt;update()&lt;/em&gt;, &lt;em&gt;delete()&lt;/em&gt;, &lt;em&gt;first()&lt;/em&gt;, &lt;em&gt;last()&lt;/em&gt;, &lt;em&gt;count()&lt;/em&gt;, &lt;em&gt;exists()&lt;/em&gt; that can be used to perform various operations on the data.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;filter()&lt;/em&gt; method is used to retrieve objects that match specific filters, &lt;em&gt;exclude()&lt;/em&gt; method is used to retrieve objects that do not match specific filters, &lt;em&gt;all()&lt;/em&gt; method is used to retrieve all objects in the table, &lt;em&gt;get()&lt;/em&gt; method is used to retrieve a single object that matches the filters, &lt;em&gt;create()&lt;/em&gt; method is used to create a new object in the table, &lt;em&gt;update()&lt;/em&gt; method is used to update existing objects in the table, &lt;em&gt;delete()&lt;/em&gt; method is used to delete existing objects in the table. first() method is used to retrieve the first object that matches the filters, &lt;em&gt;last()&lt;/em&gt; method is used to retrieve the last object that matches the filters, &lt;em&gt;count()&lt;/em&gt; method is used to retrieve the number of objects that match the filters, &lt;em&gt;exists()&lt;/em&gt; method is used to check if any objects exist that match the filters.&lt;/p&gt;

&lt;p&gt;These methods can be used in combination to perform more complex operations on the data. Additionally, you can chain these methods together to perform multiple operations in a single query. These methods are efficient and can be used to work with large datasets.&lt;/p&gt;

</description>
      <category>django</category>
      <category>webdev</category>
      <category>tutorial</category>
      <category>python</category>
    </item>
    <item>
      <title>Writing maintainable js code</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Mon, 12 Dec 2022 13:55:56 +0000</pubDate>
      <link>https://forem.com/ajmalp5/writing-maintainable-js-code-2b01</link>
      <guid>https://forem.com/ajmalp5/writing-maintainable-js-code-2b01</guid>
      <description>&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Keep your code organized and modular. This means using appropriate design patterns, such as object-oriented programming or functional programming, and dividing your code into small, manageable chunks that each have a specific purpose.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use descriptive and meaningful names for your variables, functions, and other code elements. This makes it easier for other people (or even yourself) to understand what your code is doing and how it works.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Write clear and concise comments to document your code. This can help others (or yourself) understand the purpose and behavior of your code, especially when the code itself is complex or difficult to understand.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Write tests for your code to ensure that it works as intended and to prevent regressions. This can help you catch bugs and other issues before they become a problem in production.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Follow best practices and coding standards. This can help you write code that is consistent, predictable, and easy to read and understand. There are many different coding standards and best practices that you can follow, so choose the ones that are most relevant to your project and team.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>gratitude</category>
    </item>
    <item>
      <title>To create a timer in a React app using TypeScript and Moment.js</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Mon, 12 Dec 2022 13:46:15 +0000</pubDate>
      <link>https://forem.com/ajmalp5/to-create-a-timer-in-a-react-app-using-typescript-and-momentjs-3370</link>
      <guid>https://forem.com/ajmalp5/to-create-a-timer-in-a-react-app-using-typescript-and-momentjs-3370</guid>
      <description>&lt;p&gt;To create a timer in a React app using TypeScript and Moment.js, you can use the setInterval() method from the window object, along with Moment.js's duration and add methods to calculate the remaining time.&lt;/p&gt;

&lt;p&gt;Here is an example of how you might implement a timer in a React component using TypeScript and Moment.js:&lt;br&gt;
&lt;/p&gt;

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

const MyComponent: React.FC = () =&amp;gt; {
  const [timeLeft, setTimeLeft] = useState(moment.duration(5, 'minutes'))

  // Use the useEffect hook to set up the timer
  useEffect(() =&amp;gt; {
    const interval = setInterval(() =&amp;gt; {
      setTimeLeft(timeLeft =&amp;gt; timeLeft.subtract(1, 'seconds'))
    }, 1000)

    // Clean up the interval when the component unmounts
    return () =&amp;gt; clearInterval(interval)
  }, [])

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Time left: {timeLeft.minutes()}:{timeLeft.seconds()}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the useEffect hook is used to set up the setInterval() method when the component is mounted. The setTimeLeft callback function is used to subtract one second from the timeLeft state variable every second, using Moment.js's duration and subtract methods. This causes the component to re-render with the updated time remaining.&lt;/p&gt;

&lt;p&gt;Note that the useEffect hook takes an array of dependencies as its second argument. In this case, we've passed an empty array to indicate that the effect should only run once when the component is mounted. This is important, as it prevents the timer from being reset every time the component re-renders.&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>tutorial</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Custom hooks are user-defined functions.</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Mon, 12 Dec 2022 11:27:44 +0000</pubDate>
      <link>https://forem.com/ajmalp5/custom-hooks-are-user-defined-functions-38de</link>
      <guid>https://forem.com/ajmalp5/custom-hooks-are-user-defined-functions-38de</guid>
      <description>&lt;p&gt;Custom hooks are user-defined functions that allow you to reuse stateful logic between React components. They are a powerful feature of React that can help you write cleaner, more modular code.&lt;/p&gt;

&lt;p&gt;Here are a few examples of custom hooks that you might use in a React application:&lt;/p&gt;

&lt;p&gt;useForm: This hook allows you to manage the state of a form, including the values of form fields and the validation errors. It can be used to create reusable form components that can be used in multiple places in your application.&lt;/p&gt;

&lt;p&gt;useFetch: This hook allows you to fetch data from an API and manage the state of the data, including loading, error, and success states. It can be used to create reusable data fetching components that can be used in multiple places in your application.&lt;/p&gt;

&lt;p&gt;useLocalStorage: This hook allows you to save and retrieve data from the browser's local storage. It can be used to persist data between page refreshes or sessions, and it can be used to create components that can be used to save and load data from local storage.&lt;/p&gt;

&lt;p&gt;useWindowSize: This hook allows you to detect the size of the browser window and respond to changes in window size. It can be used to create responsive components that adjust their layout or behavior based on the size of the window.&lt;/p&gt;

&lt;p&gt;Overall, custom hooks are a powerful feature of React that can help you write cleaner, more modular code. They allow you to extract stateful logic from your components and reuse it in multiple places, making your code easier to read and maintain.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>is zustand is alternative for redux?</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Mon, 12 Dec 2022 11:21:58 +0000</pubDate>
      <link>https://forem.com/ajmalp5/is-zustand-is-alternative-for-redux-4b58</link>
      <guid>https://forem.com/ajmalp5/is-zustand-is-alternative-for-redux-4b58</guid>
      <description>&lt;p&gt;Zustand is a state management library for React applications that is often compared to Redux. Both Zustand and Redux provide a way to manage state in React applications, but they have some key differences in their approach and features.&lt;/p&gt;

&lt;p&gt;One key difference between Zustand and Redux is the way that they handle state updates. Zustand uses a React hook called useState to manage state updates, while Redux uses a pattern called "reducer" to handle state updates. This means that Zustand may be easier to learn and use for developers who are familiar with React's built-in hooks, while Redux may be a better fit for developers who prefer the reducer pattern.&lt;/p&gt;

&lt;p&gt;Another difference between the two libraries is their approach to performance. Zustand uses memoization to optimize state updates, which can help improve performance in larger applications. Redux, on the other hand, uses a technique called "normalization" to optimize state updates, which can help improve the predictability and maintainability of state in large applications.&lt;/p&gt;

&lt;p&gt;Overall, Zustand and Redux are both popular state management libraries for React applications, and they both have their own strengths and weaknesses. Whether Zustand is a suitable alternative to Redux for your project will depend on your specific needs and preferences. It may be helpful to try out both libraries and see which one works best for your project.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Redux example:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As you can see, the Redux implementation is somewhat more verbose and requires more boilerplate code. You have to create a store using the createStore function, define a reducer function that specifies how the state should be updated in response to different actions, and dispatch actions to the store to update the state.&lt;/p&gt;

&lt;p&gt;In contrast, Zustand allows you to define the state and methods directly in the store, and provides a hook that you can use in your components to access the state and methods from the store. This makes it much simpler and more intuitive to manage the state of your React components.&lt;/p&gt;

&lt;p&gt;Of course, Redux offers more features and flexibility than Zustand, so it may be a better choice for certain types of applications. However, for many simple applications, Zustand can be a more convenient and lightweight solution.&lt;br&gt;
&lt;/p&gt;

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

const initialState = {
  count: 0
};

function reducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

const store = createStore(reducer);

function Counter() {
  const { count } = store.getState();
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; store.dispatch({ type: 'DECREMENT' })}&amp;gt;-&amp;lt;/button&amp;gt;
      {count}
      &amp;lt;button onClick={() =&amp;gt; store.dispatch({ type: 'INCREMENT' })}&amp;gt;+&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Zustand example:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this example, we use the create function from Zustand to create a store that manages the state of a simple counter component. The store has a count property that tracks the current value of the counter, and two methods increment and decrement that can be used to update the value of the counter.&lt;/p&gt;

&lt;p&gt;In the Counter component, we use the useStore hook provided by Zustand to access the state and methods from the store, and we use them to render the counter and add logic for incrementing and decrementing the count.&lt;/p&gt;

&lt;p&gt;This is just a simple example, but it shows how Zustand can be used to manage the state of a React application in a convenient and straightforward way.&lt;br&gt;
&lt;/p&gt;

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

const [useStore] = create((set, get) =&amp;gt; ({
  count: 0,
  increment: () =&amp;gt; set(state =&amp;gt; ({ count: state.count + 1 })),
  decrement: () =&amp;gt; set(state =&amp;gt; ({ count: state.count - 1 }))
}));

function Counter() {
  const { count, increment, decrement } = useStore();
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={decrement}&amp;gt;-&amp;lt;/button&amp;gt;
      {count}
      &amp;lt;button onClick={increment}&amp;gt;+&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>zustand</category>
      <category>webdev</category>
      <category>react</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>8 practical tips to boost the on-page SEO in no time</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Mon, 12 Dec 2022 11:12:57 +0000</pubDate>
      <link>https://forem.com/ajmalp5/8-practical-tips-to-boost-the-on-page-seo-in-no-time-44el</link>
      <guid>https://forem.com/ajmalp5/8-practical-tips-to-boost-the-on-page-seo-in-no-time-44el</guid>
      <description>&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Start by optimizing your page titles and meta descriptions. These are the first things that search engines and users see when they find your page in the search results, so they should be descriptive and compelling.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use your primary keyword in the title and meta description, but avoid keyword stuffing. Instead, focus on creating a natural, readable title and description that accurately describes the content on your page.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;3 .Optimize your page URLs by including your primary keyword and making them short, descriptive, and easy to read. Avoid using long, complex URLs with lots of numbers and special characters.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Use header tags (H1, H2, etc.) to structure your content and make it easy for users and search engines to understand the main points and topics on your page. Use your primary keyword in the H1 tag and include it in other header tags as well, but avoid keyword stuffing.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Write high-quality, unique content that is relevant to your primary keyword and the needs of your target audience. Avoid duplicate content and focus on providing value to your readers.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use images and videos to enhance your content and make it more engaging for users. Optimize your images with descriptive, keyword-rich file names and alt text, and use captions and transcriptions for videos to make them accessible to search engines.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Optimize your internal and external links by using descriptive, keyword-rich anchor text and linking to high-quality, relevant websites. Avoid using generic, vague anchor text like "click here" or "learn more" and avoid linking to low-quality, spammy websites.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Monitor and track your on-page SEO performance using tools like Google Search Console and analytics software. This will help you understand how well your on-page SEO efforts are working and identify areas for improvement.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>seo</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Should people use AI to develop Websites?</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Mon, 12 Dec 2022 11:10:40 +0000</pubDate>
      <link>https://forem.com/ajmalp5/should-people-use-ai-to-develop-websites-1bbh</link>
      <guid>https://forem.com/ajmalp5/should-people-use-ai-to-develop-websites-1bbh</guid>
      <description>&lt;p&gt;Whether or not to use AI to develop websites is a decision that ultimately depends on the specific needs and goals of the project. AI can offer some potential benefits for website development, such as helping to automate repetitive tasks and generate design ideas, but it also has some limitations that may make it less suitable for certain projects.&lt;/p&gt;

&lt;p&gt;One potential benefit of using AI to develop websites is that it can help automate repetitive tasks and save time. For example, AI can be used to generate code for common website elements, such as navigation menus and buttons, freeing up developers to focus on more complex tasks. AI can also be used to generate design ideas and layouts, helping to speed up the design process.&lt;/p&gt;

&lt;p&gt;However, AI also has some limitations that may make it less suitable for certain projects. For example, AI algorithms may not always produce high-quality or aesthetically pleasing designs, and they may not be able to capture the unique vision and style of a human designer. AI can also be expensive and time-consuming to implement, and it may require specialized knowledge and expertise to use effectively.&lt;/p&gt;

&lt;p&gt;Ultimately, whether or not to use AI to develop websites is a decision that should be made based on the specific needs and goals of the project. While AI can offer some potential benefits, it may not be the best fit for every project, and it's important to carefully consider the pros and cons before deciding to use it.&lt;/p&gt;

</description>
      <category>startup</category>
      <category>ai</category>
      <category>beginners</category>
      <category>saas</category>
    </item>
    <item>
      <title>Zustand vs Jotai, which is best state management?</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Mon, 12 Dec 2022 11:09:06 +0000</pubDate>
      <link>https://forem.com/ajmalp5/zustand-vs-jotai-which-is-best-state-management-2odb</link>
      <guid>https://forem.com/ajmalp5/zustand-vs-jotai-which-is-best-state-management-2odb</guid>
      <description>&lt;p&gt;&lt;strong&gt;Zustand&lt;/strong&gt; and &lt;strong&gt;Jotai&lt;/strong&gt; are both state management libraries for React applications. They both provide a simple, lightweight way to manage state in React components, but they have some key differences that may make one a better fit for your project than the other.&lt;/p&gt;

&lt;p&gt;One key difference between Zustand and Jotai is the way that they handle state updates. Zustand uses a React hook called useState to manage state updates, while Jotai uses a custom hook called useReducer that is based on the reducer pattern. This means that Zustand may be easier to learn and use for developers who are familiar with React's built-in hooks, while Jotai may be a better fit for developers who prefer the reducer pattern.&lt;/p&gt;

&lt;p&gt;Another difference between the two libraries is their approach to performance. Zustand uses memoization to optimize state updates, which can help improve performance in larger applications. Jotai, on the other hand, uses a technique called "time slicing" to split state updates into smaller chunks and distribute them over multiple frames, which can help improve the user experience in applications with complex state updates.&lt;/p&gt;

&lt;p&gt;Ultimately, the best state management library for your project will depend on your specific needs and preferences. Both Zustand and Jotai are popular, well-documented libraries that provide a simple, lightweight way to manage state in React applications. It may be helpful to try out both libraries and see which one works best for your project.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>To create a new project with Vite and React</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Mon, 12 Dec 2022 10:53:57 +0000</pubDate>
      <link>https://forem.com/ajmalp5/to-create-a-new-project-with-vite-and-react-42h1</link>
      <guid>https://forem.com/ajmalp5/to-create-a-new-project-with-vite-and-react-42h1</guid>
      <description>&lt;p&gt;To create a new project with Vite and React, you can use the create-vite-app command. This will create a new project with the latest versions of Vite and React, as well as any other dependencies that your project requires.&lt;/p&gt;

&lt;p&gt;Here's an example of how to create a new Vite and React project:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Install the create-vite-app package globally:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g create-vite-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Use the create-vite-app command to create a new project. For example, to create a project named my-project, you would run:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;create-vite-app my-project
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a new directory called my-project with the files and dependencies needed for your Vite and React project.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Navigate to the my-project directory and run npm install to install the project's dependencies:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd my-project
npm install
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Once the dependencies have been installed, you can start the development server by running npm run dev:
&lt;/li&gt;
&lt;/ol&gt;

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

&lt;/div&gt;



&lt;p&gt;This will start the development server and open your project in a new browser window. You can then edit the files in your project and see the changes live in the browser.&lt;/p&gt;

&lt;p&gt;That's it! You now have a new Vite and React project that you can use to build your application. For more information on how to use Vite and React, please see the Vite and React documentation.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>To create an email template for a time off approval request in Django</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Mon, 12 Dec 2022 10:48:46 +0000</pubDate>
      <link>https://forem.com/ajmalp5/to-create-an-email-template-for-a-time-off-approval-request-in-django-35ck</link>
      <guid>https://forem.com/ajmalp5/to-create-an-email-template-for-a-time-off-approval-request-in-django-35ck</guid>
      <description>&lt;p&gt;To create an email template for a time off approval request in Django, you can use the django.core.mail module to define the email's subject, message, and recipient. Here is an example of a time off approval email template in Django:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.core.mail import EmailMessage

def send_time_off_approval_email(employee, start_date, end_date):
  subject = 'Time off request approved'
  message = (
    f'Dear {employee.name},\n\n'
    f'Your time off request from {start_date} to {end_date} has been approved. '
    'Please let your manager know if you have any questions.\n\n'
    'Best regards,\n'
    'HR team'
  )
  to = [employee.email]
  email = EmailMessage(subject, message, to=to)
  email.send()

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

&lt;/div&gt;



&lt;p&gt;In this example, the send_time_off_approval_email function takes the employee's name, start date, and end date as arguments and uses them to create the email's subject and message. The function then sends the email using Django's EmailMessage class and the send method.&lt;/p&gt;

&lt;p&gt;To use this template in your Django application, you would call the send_time_off_approval_email function whenever an employee's time off request is approved, passing in the employee's information and the start and end dates of the time off. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;send_time_off_approval_email(employee, '2022-12-01', '2022-12-05')

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

&lt;/div&gt;



&lt;p&gt;This would send an email to the employee with the subject "Time off request approved" and a message thanking them for their time off request and letting them know that it has been approved.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>To create a login page for a React application.</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Mon, 12 Dec 2022 10:47:45 +0000</pubDate>
      <link>https://forem.com/ajmalp5/to-create-a-login-page-for-a-react-application-2d6</link>
      <guid>https://forem.com/ajmalp5/to-create-a-login-page-for-a-react-application-2d6</guid>
      <description>&lt;p&gt;To create a login page for a React application, you will need to use React components to create the page's layout and form elements. You can then use React's onChange event to track input from the user, and React's state to store the entered information. When the user submits the form, you can use React's onSubmit event to handle the login request and either redirect the user to the protected page or display an error message if the login fails.&lt;br&gt;
&lt;/p&gt;

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

function LoginPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [errorMessage, setErrorMessage] = useState('');

  function handleSubmit(event) {
    event.preventDefault();

    // Check the entered username and password against your database or authentication service
    if (username === 'test' &amp;amp;&amp;amp; password === 'password') {
      // Redirect the user to the protected page
      window.location.href = '/protected';
    } else {
      // Display an error message if the login fails
      setErrorMessage('Invalid username or password.');
    }
  }

  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      {errorMessage &amp;amp;&amp;amp; &amp;lt;p className="error"&amp;gt;{errorMessage}&amp;lt;/p&amp;gt;}
      &amp;lt;label&amp;gt;
        Username:
        &amp;lt;input
          type="text"
          value={username}
          onChange={(event) =&amp;gt; setUsername(event.target.value)}
        /&amp;gt;
      &amp;lt;/label&amp;gt;
      &amp;lt;label&amp;gt;
        Password:
        &amp;lt;input
          type="password"
          value={password}
          onChange={(event) =&amp;gt; setPassword(event.target.value)}
        /&amp;gt;
      &amp;lt;/label&amp;gt;
      &amp;lt;button type="submit"&amp;gt;Login&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  );
}

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

&lt;/div&gt;



&lt;p&gt;In this example, the LoginPage component uses React's useState hook to store the entered username and password, as well as any error messages that need to be displayed. The handleSubmit function is called when the user submits the form, and it checks the entered username and password against a database or authentication service. If the login is successful, the user is redirected to the protected page. If the login fails, an error message is displayed.&lt;/p&gt;

</description>
      <category>womenintech</category>
      <category>discuss</category>
    </item>
    <item>
      <title>React Form Validation</title>
      <dc:creator>Mohamed Ajmal P</dc:creator>
      <pubDate>Fri, 03 Jun 2022 06:20:38 +0000</pubDate>
      <link>https://forem.com/ajmalp5/react-form-validation-1k3h</link>
      <guid>https://forem.com/ajmalp5/react-form-validation-1k3h</guid>
      <description>&lt;p&gt;React Form Validation&lt;/p&gt;

&lt;p&gt;Before submitting data to the server, it is important to ensure all required form controls are filled out, in the correct format. This is called client-side form validation, and helps ensure data submitted matches the requirements set forth in the various form controls.&lt;/p&gt;

&lt;p&gt;This article teaches basic React form validation using controlled state inside of components. We use classes and plan to have a follow up article on doing the same thing with React Hooks.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I think you can all catch up from below code,&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

class App extends Component {
  render() {
    return (
      &amp;lt;Register /&amp;gt;
    );
  }
}

const validEmailRegex = RegExp(/^(([^&amp;lt;&amp;gt;()\[\]\.,;:\s@\"]+(\.[^&amp;lt;&amp;gt;()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^&amp;lt;&amp;gt;()[\]\.,;:\s@\"]+\.)+[^&amp;lt;&amp;gt;()[\]\.,;:\s@\"]{2,})$/i);


const validateForm = (errors) =&amp;gt; {
  let valid = true;
  Object.values(errors).forEach(
    (val) =&amp;gt; val.length &amp;gt; 0 &amp;amp;&amp;amp; (valid = false)
  );
  return valid;
}

class Register extends Component {
  constructor(props) {
    super(props);

    this.state = {
      fullName: null,
      email: null,
      password: null,
      errors: {
        fullName: '',
        email: '',
        password: '',
      }
    };

  }

  handleChange = (event) =&amp;gt; {
    event.preventDefault();
    const { name, value } = event.target;
    let errors = this.state.errors;

    switch (name) {
      case 'fullName': 
        errors.fullName = 
          value.length &amp;lt; 5
            ? 'Full Name must be 5 characters long!'
            : '';
        break;
      case 'email': 
        errors.email = 
          validEmailRegex.test(value)
            ? ''
            : 'Email is not valid!';
        break;
      case 'password': 
        errors.password = 
          value.length &amp;lt; 8
            ? 'Password must be 8 characters long!'
            : '';
        break;
      default:
        break;
    }

    this.setState({errors, [name]: value});
  }

  handleSubmit = (event) =&amp;gt; {
    event.preventDefault();
    if(validateForm(this.state.errors)) {
      console.info('Valid Form')
    }else{
      console.error('Invalid Form')
    }
  }

  render() {
    const {errors} = this.state;
    return (
      &amp;lt;div className='wrapper'&amp;gt;
        &amp;lt;div className='form-wrapper'&amp;gt;
          &amp;lt;h2&amp;gt;Create Account&amp;lt;/h2&amp;gt;
          &amp;lt;form onSubmit={this.handleSubmit} noValidate&amp;gt;
            &amp;lt;div className='fullName'&amp;gt;
              &amp;lt;label htmlFor="fullName"&amp;gt;Full Name&amp;lt;/label&amp;gt;
              &amp;lt;input type='text' name='fullName' onChange={this.handleChange} noValidate /&amp;gt;
              {errors.fullName.length &amp;gt; 0 &amp;amp;&amp;amp; 
                &amp;lt;span className='error'&amp;gt;{errors.fullName}&amp;lt;/span&amp;gt;}
            &amp;lt;/div&amp;gt;
            &amp;lt;div className='email'&amp;gt;
              &amp;lt;label htmlFor="email"&amp;gt;Email&amp;lt;/label&amp;gt;
              &amp;lt;input type='email' name='email' onChange={this.handleChange} noValidate /&amp;gt;
              {errors.email.length &amp;gt; 0 &amp;amp;&amp;amp; 
                &amp;lt;span className='error'&amp;gt;{errors.email}&amp;lt;/span&amp;gt;}
            &amp;lt;/div&amp;gt;
            &amp;lt;div className='password'&amp;gt;
              &amp;lt;label htmlFor="password"&amp;gt;Password&amp;lt;/label&amp;gt;
              &amp;lt;input type='password' name='password' onChange={this.handleChange} noValidate /&amp;gt;
              {errors.password.length &amp;gt; 0 &amp;amp;&amp;amp; 
                &amp;lt;span className='error'&amp;gt;{errors.password}&amp;lt;/span&amp;gt;}
            &amp;lt;/div&amp;gt;
            &amp;lt;div className='info'&amp;gt;
              &amp;lt;small&amp;gt;Password must be eight characters in length.&amp;lt;/small&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div className='submit'&amp;gt;
              &amp;lt;button&amp;gt;Create&amp;lt;/button&amp;gt;
            &amp;lt;/div&amp;gt;
          &amp;lt;/form&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
}

render(&amp;lt;App /&amp;gt;, document.getElementById('root'));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We are just scraping the surface here, there is so much more we can do when implementing custom validation. There are many solutions out there that make it easy to do do validation, but an exercise like this one although very basic helps us to understand how to get started rolling our own validation rather than relying on a third part to do so.&lt;/p&gt;

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