<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Israel Chidera - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Israel Chidera - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 16 May 2026 22:22:16 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/IsraelChiderah/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Integrate WordPress as a Headless CMS with Next.js – With Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ When building a dynamic blog website, it's common to fetch data from a content source, such as a CMS (Content Management System) like WordPress. Recently, I faced the challenge of integrating WordPress into my existing Next.js project. I had a blog h... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/integrate-wordpress-with-nextjs/</link>
                <guid isPermaLink="false">66fd0d6ead9b41bdb1ef70fd</guid>
                
                    <category>
                        <![CDATA[ WordPress ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ cms ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Wed, 02 Oct 2024 09:07:58 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727738740919/4dd5ea12-6e0c-4df9-8b8d-fc4f168b89c5.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When building a dynamic blog website, it's common to fetch data from a content source, such as a CMS (Content Management System) like WordPress.</p>
<p>Recently, I faced the challenge of integrating WordPress into my existing Next.js project. I had a blog hosted on WordPress and wanted to migrate it to my Next.js app.</p>
<p>I needed a solution that would allow me to use WordPress as a headless CMS. The goal was simple: leverage the power of WordPress for managing content while utilizing a modern frontend framework for displaying it.</p>
<p>In this article, we’ll walk through how to integrate WordPress to a Next JS app.</p>
<h2 id="heading-why-use-a-headless-cms">Why Use a Headless CMS?</h2>
<p>A headless CMS separates the content management (back-end) from the presentation layer (front-end). This gives developers more flexibility over how content is delivered and displayed, without being restricted by traditional themes or layouts.</p>
<p>It's great for performance, and scalability, offering more control over how content is rendered on the frontend. In this case, you’ll use WordPress as your content management system but display the content in a more modern and performant way using Next.js.</p>
<h2 id="heading-what-is-nextjs">What is Next.js?</h2>
<p>If you are yet to come across Next.js, it's a powerful React-based framework that makes building optimized, server-side rendered (SSR) applications much easier.</p>
<p>It offers a bunch of features out of the box like file-based routing, API routes, static site generation (SSG), and incremental static regeneration (ISR). All these make it a great choice for creating fast, SEO-friendly websites.</p>
<h2 id="heading-how-to-connect-wordpress-and-nextjs">How to Connect WordPress and Next.js</h2>
<p>When using WordPress as a headless CMS, there are two primary ways to connect your Next.js application to your WordPress backend:</p>
<ol>
<li><p><strong>WP REST API</strong>: WordPress comes with a built-in REST API, which allows you to retrieve content from WordPress in JSON format.</p>
</li>
<li><p><strong>WPGraphQL</strong>: WordPress supports headless content management through the use of GraphQL (with plugins such as <a target="_blank" href="https://www.wpgraphql.com/">WPGraphQL</a>), making it easy to query and retrieve specific content, like blog posts, for use in a front-end framework like React.</p>
</li>
</ol>
<p>While the REST API is popular, we’ll to go with WPGraphQL because it allows for more precise queries and flexibility. With GraphQL, you can ask for exactly the data you need, which can reduce the amount of data transferred and improve performance.</p>
<h3 id="heading-steps-to-connect-wordpress-and-nextjs-using-wpgraphql">Steps to Connect WordPress and Next.js Using WPGraphQL</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727738853280/6e07d4f5-d4c7-40a8-9355-804251707593.png" alt="WPGraphQL WordPress plugin page" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The first thing you need to do is to install the WPGraphQL plugin on your WordPress site. This plugin enables GraphQL API functionality within WordPress. You can install the plugin like any other by navigating to the WordPress admin dashboard.</p>
<p>First, go to <strong>Plugins</strong> and select <strong>Add New</strong>. Then, search for <strong>WPGraphQL</strong>, and once you find it, simply install and activate the plugin.</p>
<p>After installing and activating the plugin, the GraphQL IDE will appear on the WordPress dashboard. Here, you can test various queries you may need for your frontend development.</p>
<p>Let's move on to the frontend.</p>
<h3 id="heading-how-to-fetch-data-from-wpgraphql-in-nextjs">How to Fetch Data from WPGraphQL in Next.js</h3>
<p>In your Next.js project, you'll need to fetch data from the GraphQL API. Here’s a simple example using <code>graphql-request</code>:</p>
<p>1. Install <code>graphql-request</code> to make it easy to query the GraphQL API:</p>
<pre><code class="lang-bash">npm install graphql-request
</code></pre>
<p>2. In your Next.js component, create a GraphQL query to fetch the blog posts:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> BlogHeader <span class="hljs-keyword">from</span> <span class="hljs-string">'@/components/blog/BlogHeader'</span>;
<span class="hljs-keyword">import</span> BlogNewsletter <span class="hljs-keyword">from</span> <span class="hljs-string">'@/components/blog/BlogNewsletter'</span>;
<span class="hljs-keyword">import</span> BlogPosts <span class="hljs-keyword">from</span> <span class="hljs-string">'@/components/blog/BlogPosts'</span>;
<span class="hljs-keyword">import</span> Link <span class="hljs-keyword">from</span> <span class="hljs-string">'next/link'</span>;
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">import</span> { request, gql } <span class="hljs-keyword">from</span> <span class="hljs-string">"graphql-request"</span>;

<span class="hljs-keyword">const</span> query = gql<span class="hljs-string">`
{
  posts(first: 10) {
    edges {
      node {
        id
        title
        excerpt
        content
        date
        author {
          node {
            id
            name            
          }
        }
        date
        slug
        featuredImage {
          node {
            sourceUrl
          }
        }
        categories {
          edges {
            node {
              name
            }
          }
        }
      }
    }
  }
}
`</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStaticProps</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> posts: <span class="hljs-built_in">any</span> = <span class="hljs-keyword">await</span> request(<span class="hljs-string">'https://blog.intercity.ng/graphql'</span>, query);

    <span class="hljs-keyword">return</span> {
      props: { posts }
    }
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching posts:'</span>, error);
    <span class="hljs-keyword">return</span> {
      props: {
        posts: []
      }
    };
  }
}

<span class="hljs-keyword">const</span> Index = <span class="hljs-function">(<span class="hljs-params">{ posts }: { posts: <span class="hljs-built_in">any</span> }</span>) =&gt;</span> {

  <span class="hljs-keyword">return</span> (
    &lt;main className=<span class="hljs-string">"relative pb-10 pt-10 lg:pt-0 lg:mt-[-3%]"</span>&gt;
      &lt;div className=<span class="hljs-string">'t40-container w-full'</span>&gt;
        &lt;BlogHeader /&gt;
        &lt;BlogPosts posts={posts} /&gt;
        &lt;BlogNewsletter /&gt;
      &lt;/div&gt;
    &lt;/main&gt;
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Index
</code></pre>
<p>In the code above, your Next.js app fetches blog posts from your WordPress backend using GraphQL and displays them on the frontend. The GraphQL query is created to retrieve post details like the title, author, content, and featured image.</p>
<p>Using Next.js <code>getStaticProps</code>, the data is fetched at build time and passed as props to the component. The blog posts are rendered through custom components like <code>BlogHeader</code>, <code>BlogPosts</code>, and <code>BlogNewsletter</code>, making the page dynamic and efficient.</p>
<p>This demonstrates how WordPress can be used as a headless CMS for a Next.js application. Now that you have successfully integrated WordPress as a headless CMS in your Next.js application, you can continue fetching more data from the GraphQL API to enhance the functionality of your app.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>By using WordPress as a headless CMS and Next.js for the frontend, we can build a fast, SEO-friendly blog while taking advantage of WordPress’s powerful content management features.</p>
<p>Using WPGraphQL allowed us to efficiently fetch only the data we needed, giving us more control and improving the site's performance.</p>
<p>I hope this was useful. Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Secure Routes in Next.js 13 – Client-Side, Server-Side, and Middleware-Based Protection ]]>
                </title>
                <description>
                    <![CDATA[ Web applications often handle sensitive data and admin functionalities that should only be accessible to authenticated users. In such cases, route protection becomes crucial for safeguarding these routes from unauthorized access.  In this tutorial, w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/secure-routes-in-next-js/</link>
                <guid isPermaLink="false">66c8c87435adc35234e1f4bf</guid>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Tue, 17 Oct 2023 14:42:10 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/fly-d-ZNOxwCEj5mw-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Web applications often handle sensitive data and admin functionalities that should only be accessible to authenticated users. In such cases, route protection becomes crucial for safeguarding these routes from unauthorized access. </p>
<p>In this tutorial, we'll explore how to protect routes in Next.js 13 using three different methods. We'll learn how to protect routes on the client side and server side, and using middleware.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>Route protection is an essential aspect of web application development. It is very much needed while handling the authentication process of your application. </p>
<p>It involves controlling access to specific routes based on the user's authentication status. For instance, you wouldn't want an unauthenticated user to access an admin dashboard or view sensitive user data. </p>
<p>Before we embark on this journey, here are some prerequisites to ensure you get the most out of this tutorial:</p>
<ul>
<li>Basic understanding of Next.js, Node.js, and JavaScript</li>
<li>Familiarity with package managers like NPM or Yarn</li>
<li>A code editor of your choice (like Visual Studio Code)</li>
<li>Node.js and npm (or yarn) are installed on your machine.</li>
</ul>
<p>Let's briefly discuss what Next.js is. According to its official <a target="_blank" href="https://nextjs.org/docs/getting-started/installation">documentation</a>, Vercel created Next.js, a React framework primarily used for building full-stack web applications. Next.js offers various features, including file-based system routing, both client-side and server-side rendering, image optimizations, and enhanced support for TypeScript.</p>
<p>To start building web applications with Next.js, you can create a new Next.js project by using the following commands:</p>
<pre><code class="lang-js">npx create-next-app@latest
</code></pre>
<p>After a successful installation, you will receive several prompts to configure your Next.js application. I recommend selecting the app router, as it's the recommended choice for routing in Next.js 13. For this tutorial, we will be using Tailwind CSS for styling and TypeScript.</p>
<h2 id="heading-routing-in-nextjs">Routing in Next.js</h2>
<p>In contrast to React applications, which often rely on third-party packages like <strong>react-router-dom</strong> for routing, Next.js 13 features its own built-in app router. This router supports shared layouts, nested routing, loading states, error handling, and more. </p>
<p>Next.js uses a file-based routing system. This means that folders containing page.js files define routes. A folder can also contain one or more subfolders. </p>
<p>Next.js simplifies the implementation of protected routes. Before diving into how to create protected routes in Next.js, let's understand how routes are created.</p>
<h2 id="heading-how-to-create-a-route-in-nextjs">How to Create a Route in Next.js</h2>
<p>To demonstrate the different ways we can protect routes in Next.js 13, we will create routes: <strong>Home</strong>, <strong>Dashboard</strong>, <strong>Admin</strong>, <strong>Settings</strong>, and <strong>Profile</strong> page routes.</p>
<p>Let's perform some code cleanup. Remove all the code found on the <strong>"page.tsx"</strong> file of the app folder and insert the following code:</p>
<pre><code class="lang-tsx">// app/page.tsx
&lt;main className="text-center h-screen flex justify-center items-center"&gt;
      &lt;p&gt;Home page&lt;/p&gt;
 &lt;/main&gt;
</code></pre>
<p>The <strong>“page.tsx”</strong> file within the app folder will serve as the home page for this tutorial. Inside the app folder, create a "Profile" folder, and within it, create a “page.tsx” file. Add the following code:</p>
<pre><code class="lang-tsx">// profile/page.tsx

&lt;main className="text-center h-screen flex justify-center items-center"&gt;
      &lt;div&gt;
        &lt;h1&gt;Profile page&lt;/h1&gt;        
      &lt;/div&gt;
 &lt;/main&gt;
</code></pre>
<p>Repeat this process for the "Dashboard," "Admin," and "Settings" folders. Each should contain a "page.tsx" file. If you have completed this, you have successfully set up your routes.</p>
<p>As mentioned earlier, we will be discussing different ways to protect your routes.</p>
<h2 id="heading-client-side-route-protection">Client-Side Route Protection</h2>
<p>The client-side route protection is suitable for scenarios where you want to prevent unauthenticated users from accessing certain parts of your application on the client side. </p>
<p>You'd want to use this when you need a quick and straightforward way to protect routes without complex authentication processes. It's ideal for public websites or areas with minimal security requirements.  </p>
<p>We won't be using any authentication processes to keep the tutorial simple. Instead, we will create a function that stores the authentication value. </p>
<p>To streamline the authentication, create an "Auth.ts" file inside the Utils folder, which should be located at the root of the Next.js app. The file should contain the following code:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> isAuthenticated = <span class="hljs-literal">false</span>;
</code></pre>
<p>To secure your <code>Profile</code> route within a client component, we will be using <code>useLayoutEffect</code>. Let's see how it works by examining the code below:</p>
<pre><code class="lang-tsx">// profile/page.tsx

"use client";
import {isAuthenticated} from '@/Utils/Auth';
import { redirect } from 'next/navigation';
import { useLayoutEffect } from 'react';


const Profile = () =&gt; {

    useLayoutEffect(() =&gt; {
      const isAuth = isAuthenticated;
      if(!isAuth){
        redirect("/")
      }
    }, [])

  return (
    &lt;main className="text-center h-screen flex justify-center items-center"&gt;
      &lt;div&gt;
        &lt;h1&gt;Profile&lt;/h1&gt;        
      &lt;/div&gt;
    &lt;/main&gt;
  );
};


export default Profile;
</code></pre>
<p>In this code example, we have demonstrated a simple yet effective method for protecting routes within a client component. </p>
<p>By combining the <code>useLayoutEffect</code> hook with an authentication check and the <strong>redirect function</strong>, we have established a basic route protection mechanism. Unauthenticated users are redirected from the protected route to the "Home" route, enhancing the security of your application.</p>
<p>Inside the <code>Profile</code> component, we use the <code>useLayoutEffect</code> hook to check the user's authentication status when the component is mounted. We call the <code>isAuthenticated</code> function and store its result in the <code>isAuth</code> variable. </p>
<p>If the user is authenticated, <code>isAuth</code> will be true – otherwise, it will be false. We check if the user is not authenticated (that is, if <code>isAuth</code> is false). If they are not, we use the <code>redirect</code> function to send them back to the homepage or another landing page. This effectively prevents unauthenticated users from accessing the protected route.</p>
<p>Alternatively, we can refactor the code above to protect the <code>Profile</code> route by using a <strong>Higher Order Component (HOC)</strong>, which is a cleaner way to secure your route on the client side.</p>
<p>To use a HOC, we will create a file inside the "components" folder called <code>isAuth</code> and add the following code:</p>
<pre><code class="lang-tsx">// isAuth.tsx

"use client";
import { isAuthenticated } from "@/Utils/Auth";
import { useEffect } from "react";
import { redirect } from "next/navigation";


export default function isAuth(Component: any) {
  return function IsAuth(props: any) {
    const auth = isAuthenticated;


    useEffect(() =&gt; {
      if (!auth) {
        return redirect("/");
      }
    }, []);


    if (!auth) {
      return null;
    }

    return &lt;Component {...props} /&gt;;
  };
}
</code></pre>
<p>The code above defines a Higher Order Component (isAuth) that checks the user's authentication status. If the user is not authenticated, it prevents the rendering of the protected component and redirects them to the homepage. </p>
<p>This Higher Order Component will be used to protect the "Dashboard" route in our application by wrapping the protected component with it, as shown below:</p>
<pre><code class="lang-tsx">// dashboard/page.tsx

import isAuth from "@/Components/isAuth";

const Dashboard = () =&gt; {
  return (
    &lt;main className=" h-screen flex justify-center items-center"&gt;
      &lt;p&gt;Dashboard&lt;/p&gt;
    &lt;/main&gt;
  );
};


export default isAuth(Dashboard);
</code></pre>
<p>The code above integrates the <code>isAuth</code> HOC with the Dashboard component, ensuring that the dashboard is protected and can only be accessed by authenticated users. If a user is not authenticated, they will be redirected to a different route as defined by the <code>isAuth</code> HOC. </p>
<p>Hooray! We have successfully protected our routes on the client side using both <code>useLayoutEffect</code> and Higher Order Components.</p>
<h2 id="heading-server-side-route-protection">Server-Side Route Protection</h2>
<p>Server-side protection is the default for Next.js components. It's great for ensuring that server-rendered content is protected. You'd typically use it when you need to protect routes that should not be accessible to unauthenticated users, ensuring that sensitive information is not exposed.  </p>
<p>Protecting your routes on the server side is straightforward. We can agree that all components in Next.js are server components by default. You can protect your routes on the server side as shown below:</p>
<pre><code class="lang-tsx">// admin/page.tsx

import {isAuthenticated} from '@/Utils/Auth';
import { redirect } from 'next/navigation';


const Admin = () =&gt; {
    const isAuth = isAuthenticated;


    if(!isAuth) {
        redirect("/");
    }
  return (
    &lt;main className="text-center h-screen flex justify-center items-center"&gt;
      &lt;div&gt;
        &lt;h1&gt;Admin Page&lt;/h1&gt;
      &lt;/div&gt;
    &lt;/main&gt;
  );
};


export default Admin;
</code></pre>
<p>The code above demonstrates route protection on server components, ensuring that only authenticated users can access the admin page. If an unauthenticated user attempts to access this route, they will be redirected to the homepage.</p>
<h2 id="heading-middleware-based-route-protection">Middleware-Based Route Protection</h2>
<p>Middleware-based route protection in Next.js is a powerful approach to secure and control access to specific routes within a Next.js application. It involves the use of middleware functions to intercept incoming requests and enforce rules regarding route accessibility. </p>
<p>It is a powerful approach suitable for scenarios where you need fine-grained control over route access. It's often used for more complex applications, especially when dealing with sensitive data or user roles and permissions. </p>
<p>Middleware allows you to intercept requests and apply custom rules, making it perfect for enforcing strict security policies</p>
<p>This concept is crucial for ensuring that only authorized users can access protected routes, which often contain sensitive data or require specific privileges. Middleware-based route protection can be used on both the server and client components. </p>
<p>We are going to protect the “Settings” route using middleware. To do this, we will create a <code>middleware.ts</code> file. It is convention to create the middleware file in the root folder (the same level as the app or page folder) or inside the <strong>src</strong> folder, if applicable.  </p>
<p>We will then protect our <code>Settings</code> route by adding the following code:</p>
<pre><code class="lang-ts"><span class="hljs-comment">//middleware.ts</span>

<span class="hljs-keyword">import</span> { isAuthenticated } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/Utils/Auth"</span>;
<span class="hljs-keyword">import</span> { NextResponse } <span class="hljs-keyword">from</span> <span class="hljs-string">"next/server"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-keyword">type</span> { NextRequest } <span class="hljs-keyword">from</span> <span class="hljs-string">"next/server"</span>;


<span class="hljs-keyword">const</span> protectedRoutes = [<span class="hljs-string">"/settings"</span>];


<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">middleware</span>(<span class="hljs-params">req: NextRequest</span>) </span>{
  <span class="hljs-keyword">if</span> (!isAuthenticated &amp;&amp; protectedRoutes.includes(req.nextUrl.pathname)) {
    <span class="hljs-keyword">const</span> absoluteURL = <span class="hljs-keyword">new</span> URL(<span class="hljs-string">"/"</span>, req.nextUrl.origin);
    <span class="hljs-keyword">return</span> NextResponse.redirect(absoluteURL.toString());
  }
}
</code></pre>
<p>The code above provides a middleware-based approach to protecting the "Settings" page in a Next.js application. It checks if a user is not authenticated and whether the requested path matches one of the protected routes. </p>
<p>In the code above, <code>isAuthenticated</code> is imported from the @/Utils/Auth module. This function is responsible for checking the authentication status of a user. If a user is authenticated, it returns true – otherwise, it returns false. </p>
<p><code>NextResponse</code> and <code>NextRequest</code> are part of Next.js's serverless functions API for handling HTTP requests and responses.</p>
<p>An array <code>protectedRoutes</code> is defined, containing the path(s) of the route(s) that need protection. In this case, it includes the <code>/settings</code> route. The middleware function is executed before handling a request and serves as the middleware responsible for route protection.</p>
<p>Within the middleware function, it checks if the user is not authenticated (<code>!isAuthenticated</code>) and if the requested path (<code>req.nextUrl.pathname</code>) matches one of the protected routes. If both conditions are met, it constructs an absolute URL that points to the root path ("/") of the application using a new URL ("/", req.nextUrl.origin). It then uses <code>NextResponse.redirect</code> to perform a redirect to the constructed absolute URL.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Route protection is an indispensable aspect of web application development, especially when dealing with sensitive data or restricting access to specific functionalities. </p>
<p>In this tutorial, we've explored three comprehensive methods for safeguarding routes in Next.js 13, ensuring that unauthorized users are kept at bay. By implementing these techniques, you can bolster the security of your application and enhance the overall user experience.  </p>
<p>With the knowledge gained from this tutorial, you are well-equipped to protect your Next.js application's routes, creating a more secure and user-friendly experience. Whether you choose client-side, server-side, or middleware-based protection, the goal remains the same: safeguard your application's integrity and protect your users' data.  </p>
<p>If you have any questions or need further assistance, don't hesitate to explore additional resources or reach out to the Next.js community. You can also access the CodeSandbox for this tutorial <a target="_blank" href="https://codesandbox.io/p/sandbox/next-private-route-tutorial-456dmq?file=%2Fmiddleware.ts%3A9%2C2">here</a>.   </p>
<p>Happy coding and secure routing in your Next.js applications!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Kotlin VS Java – What's the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ Java is a widely popular programming language that has been used for years in various domains, including web development, mobile app development, desktop applications, and game development.  On the other hand, Kotlin is a relatively new programming l... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/kotlin-vs-java-whats-the-difference/</link>
                <guid isPermaLink="false">66c8c870fe21816c4cb75d09</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Kotlin ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Fri, 31 Mar 2023 20:21:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/emile-perron-xrVDYZRGdw4-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Java is a widely popular programming language that has been used for years in various domains, including web development, mobile app development, desktop applications, and game development. </p>
<p>On the other hand, Kotlin is a relatively new programming language that has been gaining popularity in recent years. Both languages are used to build applications for the Java Virtual Machine (JVM), but they differ in terms of syntax, features, and performance. </p>
<p>Java has been around for quite some time and has a vast community and a plethora of libraries. On the other hand, Kotlin is a relatively new language that offers contemporary features and concise syntax, which makes it an appealing alternative for developers. </p>
<p>In this article, we will discuss the differences between Kotlin and Java.</p>
<h1 id="heading-differences-between-kotlin-and-java">Differences Between Kotlin and Java</h1>
<h2 id="heading-syntax">Syntax</h2>
<p>One of the most significant differences between Kotlin and Java is the syntax. Kotlin has a more concise syntax than Java, which means that it requires less code to perform the same operations. </p>
<p>For example, let's compare the syntax for creating a class in both languages:</p>
<pre><code class="lang-java"><span class="hljs-comment">//java</span>

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> </span>{
   <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> myField;

   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyClass</span><span class="hljs-params">(<span class="hljs-keyword">int</span> myField)</span> </span>{
      <span class="hljs-keyword">this</span>.myField = myField;
   }

   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getMyField</span><span class="hljs-params">()</span> </span>{
      <span class="hljs-keyword">return</span> myField;
   }

   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setMyField</span><span class="hljs-params">(<span class="hljs-keyword">int</span> myField)</span> </span>{
      <span class="hljs-keyword">this</span>.myField = myField;
   }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-comment">//kotlin</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span></span>(<span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> myField: <span class="hljs-built_in">Int</span>) {
   <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">getMyField</span><span class="hljs-params">()</span></span> = myField
   <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">setMyField</span><span class="hljs-params">(value: <span class="hljs-type">Int</span>)</span></span> { myField = value }
}
</code></pre>
<p>As you can see, the Kotlin version is much more concise and readable than the Java version. In Kotlin, we can define the class and its fields in a single line, and the getters and setters are replaced with property accessors.</p>
<p>Additionally, Kotlin supports type inference, which means that you do not have to specify the data type of a variable explicitly.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">//kotlin</span>

<span class="hljs-keyword">val</span> myString = <span class="hljs-string">"Hello, world!"</span>
</code></pre>
<p>As seen in the Kotlin code above, we can use type inference to declare a variable without explicitly specifying its data type. The compiler will automatically determine the data type based on the value that we assign to the variable. This can make our code more concise and easier to read.</p>
<pre><code class="lang-java"><span class="hljs-comment">//java</span>

String myString = <span class="hljs-string">"Hello, world!"</span>;
</code></pre>
<p>In the Java code above, you are required to specify the data type of the variable which can make your code more verbose.</p>
<p>Here is another example showing the difference between the verbose syntax of Java and a more concise Kotlin syntax.</p>
<pre><code class="lang-java"><span class="hljs-comment">//java</span>

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloWorld</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        System.out.println(<span class="hljs-string">"Hello, World!"</span>);
    }
}
</code></pre>
<p>The code above is a simple "Hello, World!" program in Java that prints “Hello, World!” to the console.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">//kotlin</span>

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    println(<span class="hljs-string">"Hello, World!"</span>)
}
</code></pre>
<p>As you can see, the Kotlin version is much shorter and more expressive. Kotlin achieves this by eliminating unnecessary boilerplate code, such as type declarations and semicolons, and using more natural language constructs.</p>
<h2 id="heading-null-safety">Null Safety</h2>
<p>Both Kotlin and Java compile to bytecode that runs on the JVM, which means they have similar performance characteristics. </p>
<p>But Kotlin has some performance advantages over Java in certain cases. For example, Kotlin's <strong>null safety</strong> feature can help reduce the number of runtime exceptions and improve the overall performance of the application. And Kotlin's use of immutable data structures can also lead to improved performance.</p>
<p><strong>Null safety</strong> is another area where Kotlin differs from Java. In Java, it's possible to have null values assigned to a variable, which can lead to null pointer exceptions at runtime. Kotlin, on the other hand, requires you to explicitly define whether a variable can be null or not. This makes it easier to avoid null pointer exceptions during runtime. </p>
<p>For example, in Kotlin, all variables are non-null by default, meaning that they cannot hold a null value unless explicitly declared as nullable using the "?" operator. This helps to prevent null-related errors at compile-time, rather than waiting until runtime.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">//kotlin</span>

<span class="hljs-keyword">var</span> name: String = <span class="hljs-string">"John"</span> <span class="hljs-comment">// non-null variable</span>
<span class="hljs-keyword">var</span> age: <span class="hljs-built_in">Int</span>? = <span class="hljs-literal">null</span> <span class="hljs-comment">// nullable variable</span>
</code></pre>
<h2 id="heading-functional-programming">Functional Programming</h2>
<p>Another significant difference between Java and Kotlin is their support for functional programming. While Java has added some support for functional programming in recent years with the release of <strong>Java 8</strong>, Kotlin was designed from the ground up to support functional programming concepts.</p>
<p>For example, Kotlin supports lambda expressions, higher-order functions, and extension functions. These features make it easier to write code that is both concise and expressive and can help to improve code quality. Here is a code sample showing this:</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">//kotlin</span>
<span class="hljs-comment">// lambda expression</span>
<span class="hljs-keyword">val</span> list = listOf(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
<span class="hljs-keyword">val</span> doubledList = list.map { it * <span class="hljs-number">2</span> }

<span class="hljs-comment">// higher-order function</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">higherOrderFunc</span><span class="hljs-params">(x: <span class="hljs-type">Int</span>, y: <span class="hljs-type">Int</span>, f: (<span class="hljs-type">Int</span>, <span class="hljs-type">Int</span>) -&gt; <span class="hljs-type">Int</span>)</span></span>: <span class="hljs-built_in">Int</span> {
    <span class="hljs-keyword">return</span> f(x, y)
}
<span class="hljs-keyword">val</span> result = higherOrderFunc(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>) { x, y -&gt; x + y }

<span class="hljs-comment">// extension function</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-built_in">Int</span>.<span class="hljs-title">isEven</span><span class="hljs-params">()</span></span> = <span class="hljs-keyword">this</span> % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>
<span class="hljs-keyword">val</span> isFourEven = <span class="hljs-number">4</span>.isEven()
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In summary, <strong>Kotlin</strong> and <strong>Java</strong> are both awesome programming languages that have some significant differences. While Java is a more established language with a large community and extensive libraries, Kotlin provides modern features and concise syntax, making it an attractive choice for many developers. </p>
<p>Kotlin's focus on null safety and support for functional programming make it well-suited for modern application development, while Java's performance and library ecosystem make it a good choice for enterprise applications. </p>
<p>Ultimately, the choice between Java and Kotlin will depend on the specific needs of your application and your development team's preferences and skills.  </p>
<p>I hope this article was informative.<br>Happy learning.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What does => Mean in JavaScript? The Equals Greater Than Symbol aka Hashrocket Explained ]]>
                </title>
                <description>
                    <![CDATA[ Prior to the introduction of arrow functions, function expressions in JavaScript had a verbose syntax that often made code harder to read and understand.  As a more concise way of writing function expressions in JavaScript, arrow functions were intro... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-does-the-hashrocket-symbol-mean-in-javascript/</link>
                <guid isPermaLink="false">66c8c87e58265ae76d481679</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Tue, 21 Mar 2023 22:16:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/markus-spiske-AaEQmoufHLk-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Prior to the introduction of arrow functions, function expressions in JavaScript had a verbose syntax that often made code harder to read and understand. </p>
<p>As a more concise way of writing function expressions in JavaScript, arrow functions were introduced in ECMAScript 6 (ES6). They quickly gained popularity among developers due to their simplicity and readability.</p>
<p>Arrow functions are a shorthand way of defining functions in JavaScript, and they have a unique syntax that is different from traditional functions. The =&gt; symbol is used to define the function while the function's body is enclosed in curly braces. The "=&gt;" symbol is known as the "equals greater than" symbol or the <strong>hashrocket</strong>.</p>
<p>In this article, we will take an in-depth look at what the "<strong>=&gt;</strong>" symbol means in JavaScript and how it is used to create arrow functions. We will explore the syntax and structure of arrow functions, as well as their advantages. I hope you enjoy it.</p>
<h2 id="heading-what-the-gt-symbol-means">What the "=&gt;" Symbol Means</h2>
<p>The "=&gt;" symbol, also known as the equals greater than symbol or <strong>hashrocket</strong>, is a shorthand notation for defining functions in JavaScript. It is used to create a new type of function called an arrow function.</p>
<p>Arrow functions have a simpler and more concise syntax than traditional function expressions. You can use them to define anonymous functions or to pass functions as arguments to other functions.</p>
<p>Here is a basic example of where the hashrocket is used and how it is used.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> square = <span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x * x;
</code></pre>
<p>The code above shows how the hashrocket is used in an arrow function that takes a parameter and returns its square. </p>
<p>The arrow function is defined using the "=&gt;" symbol, which has a parameter, x. The function body, which calculates the square of "x", is not enclosed in curly braces and follows the arrow operator. This is the most concise way to write an arrow function.</p>
<p>Arrow functions can also have multiple parameters enclosed in parentheses and a function body enclosed in curly braces. Here is an example of an arrow function that takes two parameters and returns their sum:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sum = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>In the code above, the arrow function is defined using the "<strong>=&gt;</strong>" symbol, with the parameters "<strong>a</strong>" and "<strong>b</strong>". The function body, which calculates the sum of "<strong>a</strong>" and "<strong>b</strong>", is enclosed in curly braces and follows the hashrocket.</p>
<h2 id="heading-advantages-of-arrow-functions">Advantages of Arrow Functions</h2>
<h3 id="heading-lexical-scoping">Lexical Scoping</h3>
<p>Arrow functions in JavaScript have lexical scoping, which means they inherit variables from their parent scope. This feature makes them useful in certain programming tasks where you need to access variables in the parent scope.</p>
<p>Here's a simple example to illustrate this concept:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outerFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> outerVariable = <span class="hljs-string">"Hello, "</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunction</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">var</span> innerVariable = <span class="hljs-string">"world!"</span>;

    <span class="hljs-keyword">var</span> message = <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(outerVariable + name + <span class="hljs-string">" "</span> + innerVariable);
    };

    <span class="hljs-keyword">return</span> message();
  }

  innerFunction(<span class="hljs-string">"John"</span>);
}

outerFunction(); <span class="hljs-comment">//output: "Hello, John world!"</span>
</code></pre>
<p>In this example, we have an outer function called <code>outerFunction()</code> that declares a variable called <code>outerVariable</code> and assigns it the value of "Hello, ". The outer function also declares an inner function called <code>innerFunction(name)</code>, which has its own variable <code>innerVariable</code> and an arrow function called <code>message()</code>.</p>
<p>The arrow function <code>message()</code> logs a message to the console that includes the value of <code>outerVariable</code>, name (which is passed as an argument to <code>innerFunction()</code>), and <code>innerVariable</code>. When <code>message()</code> is called, it has access to all of these variables, even though they are defined in different scopes.</p>
<p>Finally, we call the outer function <code>outerFunction()</code>, which in turn calls <code>innerFunction("John")</code>. This results in the message "Hello, John world!" being logged to the console.</p>
<p>The example shows that the arrow function <code>message()</code> has access to variables defined in the outer and inner functions, thanks to <strong>lexical scoping</strong>. This feature makes arrow functions useful for accessing variables in the parent scope, which can simplify code and make it more readable.</p>
<h3 id="heading-useful-for-callbacks">Useful for callbacks</h3>
<p>Arrow functions are useful for callbacks. Callback functions are functions that are passed as arguments to other functions. Arrow functions are usually preferred as callback functions because arrow functions can be written more concisely and clearly than traditional function expressions.</p>
<p>For example, consider this code that uses the traditional function expression to filter an array of numbers:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-keyword">const</span> filteredNumbers = numbers.filter(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">number</span>) </span>{
  <span class="hljs-keyword">return</span> number % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>;
});
</code></pre>
<p>In this code, the function expression is a bit long and hard to read. We can simplify it using an arrow function as seen below.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-keyword">const</span> filteredNumbers = numbers.filter(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> number % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>);
</code></pre>
<p>In this version of the code, the arrow function is much shorter and easier to read, making it a great choice for callbacks.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, the arrow function syntax in JavaScript provides a more concise and simpler way of writing function expressions. It simplifies the syntax for simple functions using the <strong>=&gt;</strong> symbol and makes it easier to deal with scoping.</p>
<p>I hope this article was useful. Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Static Variables in Java – Why and How to Use Static Methods ]]>
                </title>
                <description>
                    <![CDATA[ Static variables and static methods are two important concepts in Java. Whenever a variable is declared as static, this means there is only one copy of it for the entire class, rather than each instan ]]>
                </description>
                <link>https://www.freecodecamp.org/news/static-variables-in-java/</link>
                <guid isPermaLink="false">66c8c87635adc35234e1f4c1</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Tue, 07 Mar 2023 15:57:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/markus-spiske-AaEQmoufHLk-unsplash--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Static variables and static methods are two important concepts in Java.</p>
<p>Whenever a variable is declared as static, this means there is only one copy of it for the entire class, rather than each instance having its own copy. A static method means it can be called without creating an instance of the class.</p>
<p>Static variables and methods in Java provide several advantages, including memory efficiency, global access, object independence, performance, and code organization.</p>
<p>In this article, you will learn how static variables work in Java, as well as why and how to use static methods.</p>
<h2 id="heading-the-static-keyword-in-java">The Static Keyword in Java</h2>
<p>The static keyword is one of the most essential features in the Java programming language. We use it to define class-level variables and methods.</p>
<p>Here is an example of how to use the static keyword:</p>
<pre><code class="language-java">public class StaticKeywordExample {
  private static int count = 0; // static variable  

  public static void printCount() { // static method
    System.out.println("Number of Example objects created so far: " + count);
  }
}
</code></pre>
<p>As you can see above, we declared the <strong>count</strong> variable as a static variable, while we declared the <strong>printCount</strong> method as a static method.</p>
<p>When a variable is declared static in Java programming, it means that the variable belongs to the class itself rather than to any specific instance of the class. This means that there is only one copy of the variable in memory, regardless of how many instances of the class are created.</p>
<p>Here's an example. Say we have a <strong>Department</strong> class that has a static variable called <code>numberOfWorker</code>. We declare and increment the static variable at the constructor level to show the value of the static variable whenever the class object is created.</p>
<pre><code class="language-java">public class Department{
    public static int numberOfWorker= 0;
    public String name;
    
    public Department(String name) {
        this.name = name;
        numberOfWorker++; // increment the static variable every time a new 							//Person is created
    }
}
</code></pre>
<p>The results of the above code show that as we create new Department objects, the static variable <code>numberOfWorker</code> retains its value.</p>
<p>When we print out the value of <code>numberOfWorker</code> in the console, we can see that it retains its value across all instances of the <code>Department</code> class. This is because there is only one copy of the variable in memory, and any changes to the variable will be reflected across all instances of the class.</p>
<pre><code class="language-java">Department dpt1 = new Department("Admin");
System.out.println(Department.numberOfWorker); // output: 1

Department dpt2 = new Department ("Finance");
System.out.println(Department.numberOfWorker); // output: 2

Department dpt3 = new Department ("Software");
System.out.println(Department.numberOfWorker); // output: 3
</code></pre>
<p>We can also use the <code>static</code> keyword to define static methods.</p>
<p>Static methods are methods that belong to the class rather than to any specific instance of the class. Static methods can be called directly on the class itself without needing to create an instance of the class first. See the code below:</p>
<pre><code class="language-java">public class Calculation{
    public static int add(int a, int b) {
        return a + b;
    }

    public static int multiply(int a, int b) {
        return a * b;
    }
}
</code></pre>
<p>In the above code, the <code>Calculation</code> class has two static methods. The declared static methods can be called directly on the Calculation class without creating an instance of the class first. That is to say, you do not need to create an object of the Calculation class before you access the static <code>add</code> and <code>multiply</code> classes.</p>
<pre><code class="language-java">int result = Calculation.add(5, 10);
System.out.println(result); // Output: 15

int result2 = Calculation.multiply(5, 10);
System.out.println(result2); // Output: 50
</code></pre>
<p>The <code>main()</code> method in Java is an example of a static method. The <code>main()</code> method is a special static method that is the entry point for Java applications. The <code>Math</code> class in Java also provides many static methods that perform mathematical operations.</p>
<pre><code class="language-java">public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");

        int result = Math.max(5, 10);
        System.out.println(result); // Output: 10

    }
}
</code></pre>
<p>The above code shows that the entry point for Java applications is a static method. It also shows that the <code>max()</code> method is a static method of the Math class and does not require an instance of the Math class to be created.</p>
<p>As you can see, static methods can be useful in providing utility functions that do not necessitate the creation of a class object.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The static keyword is a powerful tool in Java that can help solve many programming challenges. It aids in memory consumption management, improves code consistency, and helps speed up applications.</p>
<p>To prevent unforeseen issues from cropping up in the code, it is crucial to use the static keyword wisely and be aware of its limitations.</p>
<p>Code that relies heavily on static variables and methods can be harder to test because it introduces dependencies between different parts of the program. Static variables and methods can introduce hidden dependencies between different parts of the program, making it harder to reason about how changes in one part of the code might affect other parts.</p>
<p>Code that relies heavily on static variables can also be less flexible and harder to extend over time. Static variables can also lead to concurrency issues if multiple threads access and modify the same variable at the same time.</p>
<p>Lastly, if a static variable is not properly released or disposed of when it is no longer needed, it can lead to memory leaks and other performance issues over time.</p>
<p>By using static variables and methods appropriately, you can create efficient and maintainable code that will be easier to work with over time.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Convert a String to an Integer in C# – with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ There are various situations where you need to convert a string to a number. Whether you are working with user input or data from an external source, converting a string to a number is a common task for developers. This article will explore some of t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-convert-a-string-to-an-integer-in-c-sharp/</link>
                <guid isPermaLink="false">66c8c85d073b3e2196fec37b</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Thu, 23 Feb 2023 23:22:15 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/luca-bravo-XJXWbfSo2f0-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are various situations where you need to convert a string to a number. Whether you are working with user input or data from an external source, converting a string to a number is a common task for developers.</p>
<p>This article will explore some of the most common methods to convert a string to an integer in C# using the <strong><code>int.Parse()</code></strong>, <strong><code>int.TryParse()</code></strong>, and <strong><code>Convert.ToInt32()</code></strong> methods. </p>
<p>This article will also provide examples to help you understand the syntax of each method. Whether you are a beginner or an experienced programmer, this guide will provide a user-friendly introduction to the topic.</p>
<p>The <strong><code>Int</code></strong> keyword is an alias for the <strong><code>System.Int32</code></strong> type, and it is utilized for declaring variables that can hold 32-bit signed integers within the range of -2,147,483,648 to 2,147,483,647. <strong><code>Int32</code></strong> is a built-in value type that represents a 32-bit signed integer. You can convert a string to an Int using the following method.</p>
<h2 id="heading-how-to-convert-a-string-to-an-int-using-int32parse">How to Convert a String to an Int Using <code>Int32.Parse()</code></h2>
<p><code>Int32.Parse()</code> is the easiest way to convert a string to an integer. It takes a string as a parameter. Here is an example:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">string</span> numberString = “<span class="hljs-number">8</span>”;
<span class="hljs-keyword">int</span> i = <span class="hljs-keyword">int</span>.Parse(numberString); 
Console.WriteLine(<span class="hljs-string">"Value of i: {0}"</span>, i);
</code></pre>
<p>The above code shows how to convert a string to an Integer using the <strong><code>int.Parse()</code></strong> method. The method takes a string variable called <strong><code>numberString</code></strong> and converts it to an int. </p>
<p>The downside of using the <strong><code>int.Parse()</code></strong> method is that an exception will be thrown if it cannot be successfully parsed to an integer. To avoid this issue, you can use a try-catch block while using <strong><code>int.Parse()</code></strong>. Here is how to do this:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">string</span> numString = <span class="hljs-string">"12"</span>; 
<span class="hljs-keyword">try</span>
{
    <span class="hljs-keyword">int</span> num = <span class="hljs-keyword">int</span>.Parse(numString);              
}
<span class="hljs-keyword">catch</span>(FormatException ex)
{
    Console.WriteLine(ex.Message);                
}
</code></pre>
<p>Another possible solution is using <strong><code>TryParse()</code></strong>, which we'll discuss below.</p>
<h2 id="heading-how-to-convert-a-string-to-an-int-using-converttoint32">How to Convert a String to an Int Using <code>Convert.ToInt32()</code></h2>
<p><code>Convert.ToInt32()</code> is a static method provided by C# to convert a string to a 32-bit signed integer. This method takes a string variable as input and returns an integer. Here is an example:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">string</span> numString = <span class="hljs-string">"123"</span>;
<span class="hljs-keyword">int</span> num = Convert.ToInt32(numString);
</code></pre>
<p>In the code block above, we have declared a string variable, <strong><code>numString</code></strong>, and assigned it a value. We then use the <strong><code>Convert.ToInt32()</code></strong> method to convert this string to an integer and assign it to a variable named <strong><code>num</code></strong>. </p>
<p>The <code>Convert.ToInt32()</code> method has two exceptions, <strong><code>FormatException</code></strong> and <strong><code>OverflowException</code></strong> and is able to convert a null variable to 0 without throwing an exception.</p>
<h2 id="heading-how-to-convert-a-string-to-an-int-using-int32tryparse">How to Convert a String to an Int Using <code>Int32.TryParse()</code></h2>
<p>Compared to the <strong><code>int.Parse()</code></strong> method, <strong><code>int.TryParse()</code></strong> is a safer way to convert a string to a 32-bit signed integer. </p>
<p>This method takes in a string variable and an <strong><code>out</code></strong> parameter and returns a <strong><code>bool</code></strong> of value <code>true</code> if the parsing is successful. The result of the parsing is stored in an <strong><code>out</code></strong> parameter. </p>
<p>This is the safest way of converting a string variable to an Integer. Here is an example:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">string</span> numString = <span class="hljs-string">"12"</span>;

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">int</span>.TryParse(numString, <span class="hljs-keyword">out</span> <span class="hljs-keyword">int</span> num))
{
    <span class="hljs-comment">// Conversion successful, do something with num.</span>
    Console.WriteLine(<span class="hljs-string">"Successful"</span>);
    Console.WriteLine(num);
}
<span class="hljs-keyword">else</span>
{
    <span class="hljs-comment">// Conversion failed, handle the error.</span>
    Console.WriteLine(<span class="hljs-string">"Unsuccessful.."</span>);
}
</code></pre>
<p>In the above code, we tried to parse a string variable called <strong><code>numString</code></strong> to an integer using the <strong><code>int.TryParse()</code></strong> method. The result is stored in the <strong><code>num</code></strong> variable if the conversion is successful. If the conversion fails, the success variable is set to false and the num variable is assigned its default value.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Converting a string to a number is a common task in programming, and C# provides various ways to accomplish this task. </p>
<p>In this article, we saw some of the methods to convert a string to an integer in C# using the <code>Parse()</code>, <code>TryParse()</code>, and <code>Convert()</code> methods. I hope this article helped you learn more about converting strings to ints in C#.  </p>
<p>Happy coding!  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Sort a List in Java – Java List Sorting Example ]]>
                </title>
                <description>
                    <![CDATA[ Sometimes data needs to be arranged in a specific order so it's easier to understand, search, and process.  We call this process sorting. Sorting refers to arranging data in a specific order using certain criteria. You can sort different types of dat... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-sort-a-list-in-java/</link>
                <guid isPermaLink="false">66c8c868073b3e2196fec37f</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Tue, 24 Jan 2023 19:22:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/kelly-sikkema-ABkfxGoB-RE-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Sometimes data needs to be arranged in a specific order so it's easier to understand, search, and process. </p>
<p>We call this process sorting. Sorting refers to arranging data in a specific order using certain criteria. You can sort different types of data, including numbers, strings, and objects. Java provides built-in methods for sorting, such as the Collections classes.  </p>
<p>Sorting data in Java could be useful in an e-commerce application where a list of products needs to be displayed to the user. The products can be sorted in various ways depending on the requirements the user sets such as price, rating, brand, and so on.</p>
<p>For example, if the user wants to see all the products sorted by price in ascending order, the application can use a sorting algorithm to arrange the products in that order. This way, when the user views the products, they will be able to see the cheapest products first and make a purchase decision accordingly.  </p>
<p>This article will look at various methods for sorting a list in Java.</p>
<h2 id="heading-how-to-use-the-collectionssort-method-in-java">How to Use the <code>Collections.Sort()</code> Method in Java</h2>
<p>One of the most common ways to sort data in Java is to use the <code>Collections.sort()</code> method. It sorts a list in ascending order by default. </p>
<p>Here is an example of how to use the <code>Collections.sort()</code> method to sort a list of integers:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Collections;
<span class="hljs-keyword">import</span> java.util.List;
<span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        List&lt;Integer&gt; numbers = <span class="hljs-keyword">new</span> ArrayList&lt;Integer&gt;();
        numbers.add(<span class="hljs-number">3</span>);
        numbers.add(<span class="hljs-number">1</span>);
        numbers.add(<span class="hljs-number">4</span>);
        numbers.add(<span class="hljs-number">2</span>);

        Collections.sort(numbers);

        System.out.println(<span class="hljs-string">"Sorted List: "</span> + numbers);
    }
}
</code></pre>
<p>The above code creates a list of integers, adds four numbers to it, sorts the list, and then prints the sorted list to the console. </p>
<p>It uses classes from the Java standard library, including <strong><code>java.util.Collections</code></strong>, <strong><code>java.util.List</code></strong>, and <strong><code>java.util.ArrayList</code></strong> to perform the operations. </p>
<p>The output of the above code is shown below:</p>
<pre><code class="lang-bash">//Output
Sorted List: [1, 2, 3, 4]
</code></pre>
<p>You can also sort a list of custom objects using the <code>Collections.sort()</code> method. To do this, you will need to create a comparator and pass it as an argument to the <code>Collections.sort()</code> method. </p>
<p>A comparator is an object that implements the <code>java.util.Comparator</code> interface. It has a single method called <code>compare()</code> that compares two objects and returns an integer indicating their relative order.</p>
<p>Here is an example of how to use a comparator to sort a list of custom objects:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Collections;
<span class="hljs-keyword">import</span> java.util.List;
<span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        List&lt;Person&gt; people = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
        people.add(<span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">25</span>));
        people.add(<span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Bob"</span>, <span class="hljs-number">30</span>));
        people.add(<span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Charlie"</span>, <span class="hljs-number">20</span>));

        Collections.sort(people, <span class="hljs-keyword">new</span> PersonComparator());

        System.out.println(<span class="hljs-string">"Sorted List: "</span> + people);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Person</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> age)</span> </span>{
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-keyword">this</span>.age = age;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> age;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> name + <span class="hljs-string">" ("</span> + age + <span class="hljs-string">")"</span>;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PersonComparator</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">Comparator</span>&lt;<span class="hljs-title">Person</span>&gt; </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">compare</span><span class="hljs-params">(Person a, Person b)</span> </span>{
        <span class="hljs-keyword">return</span> a.getAge() - b.getAge();
    }
}
</code></pre>
<p>The code above creates a list of 'Person' objects, adds several Person objects to the list, sorts the list using a custom comparator (<code>PersonComparator</code>), and then prints out the sorted list. </p>
<p>The <code>Person</code> class has two fields, <code>name</code> and <code>age</code>, and getter methods for these fields. The <code>PersonComparator</code> class implements the Comparator interface and overrides the compare method to sort <code>Person</code> objects by age.  </p>
<p>The output of this program will be the following:</p>
<pre><code class="lang-bash">//output
Sorted List: [Charlie (20), Alice (25), Bob (30)]
</code></pre>
<p>It's best to use the <strong><code>Collections.sort()</code></strong> method when you have a collection of objects that need to be sorted based on one or more fields. </p>
<p>For example, if you have a collection of Employee objects and you want to sort them by their last name, you can use the <code>Collections.sort()</code> method and pass in a custom Comparator that compares the last names of the Employee objects.</p>
<h2 id="heading-how-to-use-the-listsort-method-in-java">How to Use the List.Sort() Method in Java</h2>
<p>This method sorts a list in ascending order. Here's how it works:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        List&lt;Integer&gt; numbers = Arrays.asList(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">1</span>);
        numbers.sort(<span class="hljs-keyword">null</span>);
        System.out.println(numbers); <span class="hljs-comment">// prints [1, 2, 3, 4, 5]</span>
    }
}
</code></pre>
<p>Inside the main method above, a list of integers called "numbers" is created using the <code>Arrays.asList</code> method. The code then sorts this list of numbers using the default sorting method since null is passed to the sort method.</p>
<p>Finally, the sorted list is printed to the console using the <code>System.out.println</code> method, which will output "[1, 2, 3, 4, 5]".</p>
<p><strong><code>List.sort()</code></strong> is useful when you have a list of elements that need to be sorted. For example, if you have a list of strings and you want to sort them in alphabetical order, you can use the <code>List.sort()</code> method. </p>
<p><code>List.sort()</code> is an instance method of the List class and it sorts the elements in the order defined by their natural ordering or by a specified <code>Icomparer</code> implementation.</p>
<h2 id="heading-how-to-use-the-streamsorted-method-in-java">How to Use the <code>stream.sorted()</code> Method in Java</h2>
<p>In Java 8 and above, you can use the <strong>Stream API</strong> to sort a list. The Stream API provides a sorted method that you can use to sort the elements of a stream. </p>
<p>Here is an example of how to sort a list of integers using a stream:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;
<span class="hljs-keyword">import</span> java.util.List;
<span class="hljs-keyword">import</span> java.util.stream.Collectors;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        List&lt;Integer&gt; numbers = Arrays.asList(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">1</span>);
        List&lt;Integer&gt; sortedList = numbers.stream().sorted().collect(Collectors.toList());
        System.out.println(sortedList); <span class="hljs-comment">// prints [1, 2, 3, 4, 5]</span>

    }
}
</code></pre>
<p>In the example above, the number list is converted to a stream using the <code>stream()</code> method. The <code>sorted()</code> method is then called on the stream to sort the elements. The <code>collect(Collectors.toList())</code> method is used to collect the sorted elements back into a list. The result is a new list containing the sorted elements. The output will be "[1, 2, 3, 4, 5]".</p>
<p><strong><code>stream.sorted()</code></strong> is best used when you have a stream of elements that need to be sorted. For example, if you have a stream of integers and you want to sort them in ascending order, you can use the <code>stream.Sorted()</code> method.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned that there are several ways to sort a list in Java – the <strong>Collections.sort()</strong> method, the <strong>stream.sorted()</strong> method, and the <strong>List.sort()</strong> method. The best method to use depends on the specific requirements of the task at hand as we discussed above.</p>
<p>I hope this article has given you the correct information on how to sort a list in Java.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Functions Work in JavaScript – JS Function Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is a widely-used programming language that is essential for web development. Its ability to run on both client-side and server-side makes it a versatile tool that has become an essential tool for web developers. JavaScript is a high-level,... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understanding-functions-in-javascript/</link>
                <guid isPermaLink="false">66c8c879fe21816c4cb75d0b</guid>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Fri, 20 Jan 2023 17:52:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/kevin-ku-w7ZyuGYNpRQ-unsplash-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is a widely-used programming language that is essential for web development. Its ability to run on both client-side and server-side makes it a versatile tool that has become an essential tool for web developers.</p>
<p>JavaScript is a high-level, interpreted language used on the client side, meaning it runs in the user's web browser. You can use it to create web and mobile applications, browser extensions, and other software. </p>
<p>It is supported by all major web browsers, and it is an essential technology for front-end web development. </p>
<p><strong>Functions</strong> are one of the building blocks of JavaScript programming for creating web applications. </p>
<p>You can think of functions as a way to group a set of instructions together and execute them as a single unit. </p>
<p>In this article, we will explore the basics of functions in JavaScript and how you can use them effectively in your code.</p>
<h2 id="heading-function-syntax">Function Syntax</h2>
<p>A function is a block of code that performs a specific task. JavaScript functions are basically used to encapsulate logic, making that code more reusable and easier to understand. </p>
<p>The syntax for creating a function in JavaScript is quite simple. Functions can take input in the form of parameters and can return a value or output. </p>
<p>Functions help you organize and structure your code. They also allow for code reuse and make it easier to understand and maintain large codebases.</p>
<h3 id="heading-how-to-write-a-function-in-javascript">How to Write a Function in JavaScript</h3>
<p>You start by using the keyword "<strong>function</strong>," followed by the function name and a set of parentheses. </p>
<p>Inside the parentheses, you can specify any input parameters that the function will take in, also known as arguments. The arguments are usually optional. </p>
<p>Next, you include a block of code inside curly braces that defines the instructions the function will execute when it is called. </p>
<p>Here is an example of a basic function that takes in two numbers and returns their sum:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>The function above, named "<strong>addNumbers</strong>," takes in two parameters, <strong>a</strong> and <strong>b</strong>. The code inside the function body simply adds these two parameters together and returns the result.</p>
<h2 id="heading-how-to-declare-a-function-in-javascript">How to Declare a Function in JavaScript</h2>
<p>Apart from the regular way of declaring a function as seen above, you can also define functions using <strong>function expressions</strong> or <strong>arrow functions</strong>. </p>
<p>The arrow function syntax is a shorthand version of the regular function syntax. Here is the same function as above, but written with an arrow function:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>
<span class="hljs-keyword">const</span> addNumbers = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b;
</code></pre>
<p>In the example above, the function is assigned to the variable <strong>addNumbers</strong>. The arrow <strong>=&gt;</strong> is used to define the function, and the code inside the curly braces is the body of the function.</p>
<p>Function expressions in JavaScript are similar to regular function declarations. The difference between them is that the function expression is always assigned to a variable. Here is an example of a function expression:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>
<span class="hljs-keyword">let</span> multiplyNumbers = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a * b;
}
</code></pre>
<p>In this example, the function is assigned to the variable <strong>multiplyNumbers</strong>. This variable can be used to call the function, just like a regular function.</p>
<h2 id="heading-how-to-use-callback-functions">How to Use Callback Functions</h2>
<p>Functions can also be passed as arguments to other functions, known as <strong>callback functions</strong>. Here is an example of a callback function being used to log the result of a multiplication operation:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiplyByTwo</span>(<span class="hljs-params">n, callback</span>) </span>{
  <span class="hljs-keyword">var</span> result = n * <span class="hljs-number">2</span>;
  callback(result);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logResult</span>(<span class="hljs-params">result</span>) </span>{
  <span class="hljs-built_in">console</span>.log(result);
}

multiplyByTwo(<span class="hljs-number">5</span>, logResult); <span class="hljs-comment">// logs 10</span>
</code></pre>
<p>In this example, the <strong>multiplyByTwo</strong> function takes two arguments: a number and a callback function. The function multiplies the number by 2 and then invokes the callback function, passing the result as an argument. The <strong>logResult</strong> function is then executed, which logs the result to the console.</p>
<h2 id="heading-how-to-use-default-parameters">How to Use Default Parameters</h2>
<p>JavaScript functions also have a feature called default parameters. They allow you to set default values for parameters in case they are not passed when the function is called. </p>
<p>This is helpful in situations where you want to provide a default value for a parameter in case it is not passed. Here is an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name = <span class="hljs-string">"John Doe"</span></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
}

greet(); <span class="hljs-comment">// Hello, John Doe!</span>
greet(<span class="hljs-string">"Jane Smith"</span>); <span class="hljs-comment">// Hello, Jane Smith</span>
</code></pre>
<p>In this example, the <code>greet</code> function takes in a single parameter <code>name</code>, which is set to "John Doe" by default. If the function is called without passing any arguments, it will use the default value "John Doe". But if an argument is passed, it will use that value instead.</p>
<h2 id="heading-how-to-use-the-constructor-function">How to Use the Constructor Function</h2>
<p>JavaScript has a special type of function called a constructor function, which is used to create objects. </p>
<p>You define a constructor function using the keyword "function" followed by a name that starts with an uppercase letter (called using the "new" keyword). </p>
<p>For example, the following code defines a constructor function named "Person" that creates an object with a name and age property:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name, age</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.age = age;
}

<span class="hljs-keyword">let</span> person = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"John Smith"</span>, <span class="hljs-number">30</span>);
<span class="hljs-built_in">console</span>.log(person.name); <span class="hljs-comment">// Output: "John Smith"</span>
<span class="hljs-built_in">console</span>.log(person.age);
</code></pre>
<h2 id="heading-how-to-use-closures">How to Use Closures</h2>
<p>A <strong>closure</strong> is a function that has access to variables in its parent scope, even after the parent function has returned. This allows for variables to be preserved between function calls, and it is a powerful feature that allows for more advanced programming patterns such as object-oriented programming. </p>
<p>Here's an example of a closure function that creates a counter:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createCounter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> count++;
  }
}
<span class="hljs-keyword">const</span> myCounter = createCounter();
<span class="hljs-built_in">console</span>.log(myCounter()); <span class="hljs-comment">// Output: 0</span>
<span class="hljs-built_in">console</span>.log(myCounter()); /
</code></pre>
<h2 id="heading-how-to-use-higher-order-functions">How to Use Higher-Order Functions</h2>
<p>Functions can also be passed as arguments to other functions, which is known as a "higher-order" function. For example:</p>
<pre><code class="lang-js"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">performOperation</span>(<span class="hljs-params">a, b, operation</span>) </span>{
    <span class="hljs-keyword">return</span> operation(a, b);
}

<span class="hljs-keyword">let</span> result = performOperation(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, addNumbers);
<span class="hljs-built_in">console</span>.log(result);  <span class="hljs-comment">// 15</span>
</code></pre>
<p>In this example, the <strong>performOperation</strong> function takes in three arguments: <strong>a</strong>, <strong>b</strong>, and <strong>operation</strong>. </p>
<p>The <strong>operation</strong> argument is a function that takes in two arguments and returns a result. In this case, we are passing the <strong>addNumbers</strong> function as the operation argument, so the result of the <strong>performOperation</strong> function will be the result of calling the <strong>addNumbers</strong> function with the arguments <strong>a</strong> and <strong>b</strong>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we have covered the basics of functions in JavaScript, including how to define, call, and use them in our codes. </p>
<p>With a solid understanding of functions, you can write more efficient and maintainable code in JavaScript.</p>
<p>You can check the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions">MDN docs</a> to read more about functions in JavaScript. If you want to start learning the fundamentals of JavaScript, freeCodeCamp has a free <a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/">JavaScript Algorithms and Data Structures Certification</a> course for you.  </p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ C# Coding Best Practices – Coding Conventions with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Coding conventions ensure that your code is consistent, readable, understandable, and maintainable.  When it comes to writing clean and quality code, there are conventions developers should follow to make this possible.  There are a few things you sh... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/coding-best-practices-in-c-sharp/</link>
                <guid isPermaLink="false">66c8c85735adc35234e1f4bd</guid>
                
                    <category>
                        <![CDATA[ best practices ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Fri, 13 Jan 2023 16:31:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/kevin-ku-w7ZyuGYNpRQ-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Coding conventions ensure that your code is consistent, readable, understandable, and maintainable. </p>
<p>When it comes to writing clean and quality code, there are conventions developers should follow to make this possible. </p>
<p>There are a few things you should keep in mind while writing your code. In this article, we will learn about the best coding practices every C# developer should know.</p>
<h2 id="heading-c-naming-conventions">C# Naming Conventions</h2>
<p>There are various naming conventions you should use when following best coding practices in C#. </p>
<p>Using consistent naming conventions across a codebase can make it easier for developers to understand and navigate the code, and can help prevent naming conflicts and confusion. </p>
<p>The following naming conventions are usually observed in C# programming.</p>
<h3 id="heading-when-to-use-pascal-case">When to use Pascal case</h3>
<p>When naming a <strong>class</strong>, <strong>struct, method</strong>, <strong>property,</strong> or <strong>constant field</strong>, Pascal casing is usually preferred.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">namespace</span> <span class="hljs-title">ExampleApp</span>
{

    <span class="hljs-keyword">class</span> <span class="hljs-title">ClassNamingConvention</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> ConstantFieldNamingConvention = <span class="hljs-string">"C#"</span>;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> PropertiesNamingConvention { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">MethodNamingConvention</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-comment">//type something here</span>
        }
    }
}
</code></pre>
<p>When naming an interface, it is usually prefixed with the capital letter <strong>I</strong>. You can also use Pascal case when naming an interface.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IInterfaceNamingConvention</span>
{
        <span class="hljs-comment">//type something here</span>
}
</code></pre>
<h3 id="heading-when-to-use-camel-case">When to use Camel case</h3>
<p>Camel cases are used when naming <strong>method arguments, private fields,</strong> and <strong>local variables.</strong> Private fields are usually prefixed with _.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> _fieldsNamingConvention;

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">MethodNamingConvention</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> methodArgsNamingConvention</span>)</span>
{
     <span class="hljs-keyword">string</span> localVariables = <span class="hljs-string">"string here ..."</span>;            
}
</code></pre>
<h3 id="heading-use-meaningful-names-for-classes-methods-and-properties">Use meaningful names for classes, methods, and properties</h3>
<p>Always use meaningful and self-explanatory names for your classes, methods, and properties. It is good practice to name properties, methods, and classes with what they do. This way, just by reading the name, you can easily know what exactly it does.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">class</span> <span class="hljs-title">AppNotification</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> _appStatus;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> AppStatus
        {
            <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> _appStatus; }
            <span class="hljs-keyword">set</span> { _appStatus = <span class="hljs-keyword">value</span>; }
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SendNotification</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-comment">//type something here . . .</span>
        }
    }
</code></pre>
<h3 id="heading-use-meaningful-names-for-linq-query-variables">Use meaningful names for LINQ query variables</h3>
<p>Always use meaningful and self-explanatory names for your LINQ query variables, as seen in the example below.</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">QueryRacers</span>(<span class="hljs-params"></span>)</span>
{
     <span class="hljs-keyword">var</span> racersInItaly = <span class="hljs-keyword">from</span> racer <span class="hljs-keyword">in</span> racers
                         <span class="hljs-keyword">where</span> racer.City == <span class="hljs-string">"Lazio"</span>
                         <span class="hljs-keyword">select</span> racer.Name;
}
</code></pre>
<h2 id="heading-ia"> </h2>
<p>C# Code Layouts and Comments</p>
<h3 id="heading-how-to-declare-member-variables-and-fields">How to declare member variables and fields</h3>
<p>Always declare all your member variables and fields at the top of a class. When fields are declared at the top of a class, it is easy to see all the variables that the class is using and understand the class's overall state. </p>
<p>It's also important to declare fields at the top of a class in C# because it makes the code more organized and readable, especially when working with large classes or when working with a team. This makes it easier for others to understand the code and make changes.</p>
<pre><code class="lang-cs">    <span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> _carSpeed;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> CarSpeed
        {
            <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> _carSpeed; }
            <span class="hljs-keyword">set</span> { _carSpeed = <span class="hljs-keyword">value</span>; }
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">GetMaxSpeed</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-comment">//...</span>
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">GetMaxAcceleration</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-comment">//...</span>
        }
    }
</code></pre>
<h3 id="heading-format-and-indent-your-code-properly">Format and indent your code properly</h3>
<p>When it comes to code layout, it is important to format and properly indent your code for readability and clean code organization. </p>
<p>It is good practice to write only one statement per line. For example:</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Numbers</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> number</span>)</span>
{
       <span class="hljs-comment">//Good practice</span>
      <span class="hljs-keyword">if</span> (number &gt; <span class="hljs-number">0</span>)
      {
           Console.WriteLine(number);
       }

       <span class="hljs-comment">//Bad practice</span>
      <span class="hljs-keyword">if</span> (
            number 
              &lt; <span class="hljs-number">0</span>
          )
          {
              Console.WriteLine(number);
          }
  }
</code></pre>
<h3 id="heading-how-to-write-comments">How to write comments</h3>
<p>It is good practice to start your comments with uppercase text and end with a period. </p>
<p>Writing comments is helpful to the whole team. It makes code more readable, maintainable, and understandable. It is good practice to place comments on a new line, not at the end of your code. For example:</p>
<pre><code class="lang-cs">    <span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
        <span class="hljs-comment">//We place comments here.       </span>
        <span class="hljs-comment">//And end with a period.</span>

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Move</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-comment">//...</span>
        }
    }
</code></pre>
<h2 id="heading-general-c-coding-best-practices">General C# Coding Best Practices</h2>
<h3 id="heading-how-to-compare-a-value-to-an-empty-string">How to compare a value to an empty string</h3>
<p>Instead of " ", try <code>String.Empty</code> when comparing a value to an empty string. Using String.Empty improves code readability and makes it clear that the comparison is intended to be with an empty string. This makes it easier to understand and maintain the code in the future.</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">NameCheck</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> name</span>)</span>
{
     <span class="hljs-keyword">if</span>(name == String.Empty)
     {

      }
 }
</code></pre>
<h3 id="heading-use-exception-handling">Use exception handling</h3>
<p>Use exception handling to gracefully handle errors and exceptions. This helps prevent your code from crashing and makes it more robust. It is good practice to use a try-catch statement for most exception handling.</p>
<pre><code class="lang-cs">  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">NameCheck</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> name</span>)</span>
    {
        <span class="hljs-keyword">try</span>
        {
            <span class="hljs-comment">//type code here</span>
        }
        <span class="hljs-keyword">catch</span> (Exception exception) { }
        {
            <span class="hljs-comment">//type code here</span>
        }
    }
</code></pre>
<h3 id="heading-use-ampamp-and-for-better-performance">Use <code>&amp;&amp;</code> and <code>||</code> for better performance</h3>
<p>To increase the performance of your application, it is good practice to use <strong>&amp;&amp;</strong> instead of <strong>&amp;</strong> and <strong>||</strong> instead of <strong>|</strong> when you perform comparisons, as shown in the following example.</p>
<pre><code class="lang-cs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Numbers</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> number</span>)</span>
{
   <span class="hljs-keyword">if</span> (number &gt; <span class="hljs-number">2</span> &amp;&amp; number &lt; <span class="hljs-number">4</span>)
   {
       Console.WriteLine(number);
   }   
}
</code></pre>
<p>This is because the <code>&amp;&amp;</code> and <code>||</code> operators are known as "<strong>short-circuit</strong>" operators. This means that if the first operand of an <code>&amp;&amp;</code> operation is false, the second operand will not be evaluated because the overall expression must be false.</p>
<p>Similarly, if the first operand of an <code>||</code> operation is true, the second operand will not be evaluated because the overall expression must be true. </p>
<p>This in turn increase the performance of your program.</p>
<h3 id="heading-limit-methods-to-a-single-functionality">Limit methods to a single functionality</h3>
<p>It is best to limit your methods to a single functionality. Do not try to combine multiple functionalities of a class into a single method. This ensures code readability and helps you avoid writing "spaghetti code".</p>
<pre><code class="lang-cs">    <span class="hljs-keyword">class</span> <span class="hljs-title">AppNotification</span>
    {        
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SendNotification</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-comment">//. . .</span>
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">ReceiveNotification</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-comment">//. . .</span>
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">MuteNotification</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-comment">//. . .</span>
        }
    }
</code></pre>
<h3 id="heading-use-enums-for-discrete-values">Use enums for discrete values</h3>
<p>Use <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum">enums</a> instead of using numbers and strings to indicate discrete values. Enums provide a way to improve the quality of your code by making it more readable, type-safe, and efficient. They also provide a way to define a set of named integral constants.</p>
<pre><code class="lang-cs"> <span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">enum</span> LoggerType
        {
            NewCars,
            UsedCars,
            Database
        }
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayException</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> message, LoggerType loggerType</span>)</span>
        {
            <span class="hljs-keyword">switch</span> (loggerType)
            {
                <span class="hljs-keyword">case</span> LoggerType.NewCars:
                    Console.WriteLine(LoggerType.NewCars);
                    <span class="hljs-keyword">break</span>;

                <span class="hljs-keyword">case</span> LoggerType.UsedCars:
                    Console.WriteLine(LoggerType.UsedCars);
                    <span class="hljs-keyword">break</span>;

                <span class="hljs-keyword">case</span> LoggerType.Database:
                    Console.WriteLine(LoggerType.Database);
                    <span class="hljs-keyword">break</span>;

                <span class="hljs-keyword">default</span>:
                    Console.WriteLine(message);
                    <span class="hljs-keyword">break</span>;
            }
        }
    }
</code></pre>
<h3 id="heading-how-to-compare-string-variables-with-user-input">How to compare string variables with user input</h3>
<p>It is good practice to always convert string variables into uppercase or lowercase before comparing them with user input. </p>
<p>This ensures that the comparison is case-insensitive. This makes your code more readable and maintainable as it eliminates the need for case-handling logic.</p>
<pre><code class="lang-cs">  <span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayTransactions</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">string</span> name = Console.ReadLine();

            <span class="hljs-keyword">if</span>(name.ToLower() == <span class="hljs-string">"Joe"</span>)
            {
                <span class="hljs-comment">//...</span>
            }

            <span class="hljs-comment">//Or.</span>

            <span class="hljs-keyword">if</span> (name.ToUpper() == <span class="hljs-string">"Joe"</span>)
            {
                <span class="hljs-comment">//...</span>
            }
        }
    }
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Coding conventions ensure readability and consistency within the team's and company’s codebase.</p>
<p>There are a lot of coding conventions in C# that help to ensure code quality. You can check the Microsoft .NET <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions">documentation</a> to read more about coding conventions.</p>
<p>I hope you learnt a lot through this tutorial.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Filtering in C# – How to Filter a List with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Filtering through a data set is one of the most basic operations a developer should know how to perform.  Filtering refers to the process of restricting the result set to contain only those elements that satisfy a specified condition. It is also know... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/filtering-in-csharp-how-to-filter-a-list-with-code-examples/</link>
                <guid isPermaLink="false">66c8c85a0f021017a28a49c9</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Wed, 21 Dec 2022 21:45:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/ferenc-almasi-tvHtIGbbjMo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Filtering through a data set is one of the most basic operations a developer should know how to perform. </p>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/filtering-data">Filtering</a> refers to the process of restricting the result set to contain only those elements that satisfy a specified condition. It is also known as selection. </p>
<p>To be practical, imagine trying to search and collect oranges from a basket of fruits. That is <strong>filtering</strong>. </p>
<p>In this article, we will see different ways to filter through a List class.</p>
<p>Before we start filtering the List collection, we will create a public class called <strong>Employee</strong> that holds the employee details. </p>
<p>The Employee class is like a blueprint that holds the details for each employee. It has private fields for the <em>name</em>, <em>id</em>, and <em>department</em> of each employee. </p>
<p>The <strong>Employee</strong> class also has <em>getter</em> and <em>setter</em> methods to be able to set and get the value of each of the private field. </p>
<p>Here is the code that demonstrates what I was just explaining above:</p>
<pre><code class="lang-cs">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> _name;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> _id;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> _department;

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name
        {
            <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> _name; }
            <span class="hljs-keyword">set</span> { _name = <span class="hljs-keyword">value</span>; }
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id
        {
            <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> _id; }
            <span class="hljs-keyword">set</span> { _id = <span class="hljs-keyword">value</span>; }
        }

        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Department
        {
            <span class="hljs-keyword">get</span> { <span class="hljs-keyword">return</span> _department; }
            <span class="hljs-keyword">set</span> { _department = <span class="hljs-keyword">value</span>; }
        }
    }
</code></pre>
<p>Inside the Program class, let's create a method that will house a list using the <strong>Employee</strong> class already created above. Each employee will have an ID, a name, and a department.</p>
<pre><code class="lang-program.cs"> public static void ListOperations()
 {
     List&lt;Employee&gt; employees = new List&lt;Employee&gt;()
    {
        new Employee(){ Id=1, Name="John Doe", Department="Software"},
        new Employee(){ Id=2, Name="Angela Su", Department="Sales"},
        new Employee(){ Id=3, Name="Frank Kelvin", Department="Marketing"},
        new Employee(){ Id=4, Name="Joe Dustin", Department="Sales"},
        new Employee(){ Id=5, Name="Glory GG", Department="Software"},
        new Employee(){ Id=6, Name="Antonella Cruz", Department="Marketing"},
        new Employee(){ Id=5, Name="Andrew Logan", Department="Software"},
        new Employee(){ Id=6, Name="Billy Cruz", Department="Marketing"},
        new Employee(){ Id=5, Name="Sally Jane", Department="Software"},
        new Employee(){ Id=4, Name="Jon Snow", Department="Sales"},
    };
}
</code></pre>
<p>The above code is the declaration of a list of employees in the <strong>ListOperations method</strong>. Our goal is to filter through the list to get the employees that work in the software department.</p>
<p>There are several ways to filter through a list in C#. Let's look at them now:</p>
<h2 id="heading-how-to-filter-through-a-list-using-the-iterative-method">How to filter through a list using the iterative method</h2>
<p>In this method, you loop through a list and search for the member of each iteration that passes the condition. Below is a code sample that uses the iterative method:</p>
<pre><code class="lang-program.cs">Console.WriteLine("Filtering through the Employee list using the " +
                    "Iterative method");
//goal: Filter through the list to get employees in the company’s software //department

foreach (var employee in employees)
{
    if(employee.Department == "Software")
    {
        Console.WriteLine(employee.Name);
    }
}
</code></pre>
<h2 id="heading-how-to-filter-through-a-list-using-the-linq-query-syntax-where-clause">How to filter through a list using the LINQ query syntax (Where clause)</h2>
<p>Language-Integrated Query (LINQ) is a powerful way to retrieve data from data sources in C#. This method filters the list collection and returns a new collection based on a given criterion.</p>
<pre><code class="lang-program.cs">Console.WriteLine("\nWhere clause - LINQ query syntax ");
var filteredResults = from employee in employees
                        where employee.Department == "Software"
                        select employee.Name;

//Looping through your filtered results
foreach(var result in filteredResults)
{
    Console.WriteLine(result);
}
</code></pre>
<p>In the above code, the <strong>LINQ query syntax</strong> uses the <strong>where</strong> operator to filter the employees who are working in the <strong>Software</strong> department from the <strong>employees</strong> list. We then loop through the filtered results to print our results to the console. </p>
<h2 id="heading-how-to-filter-through-a-list-using-the-linq-method-syntax-where-clause">How to filter through a list using the LINQ method syntax (Where clause)</h2>
<p>Unlike the query syntax above, the <strong>LINQ extension method</strong> uses the lambda expression. The lambda expression is passed as a predicate. It is indeed a shortcut to the LINQ query syntax above. </p>
<p>Below is a code sample that uses the <strong>LINQ method syntax.</strong></p>
<pre><code class="lang-program.cs">Console.WriteLine("\nWhere clause - LINQ method syntax ");

var filteredResultsTwo = employees.Where(employee =&gt; employee.Department == "Software");

//Looping through your filtered results
foreach(var employee in filteredResultsTwo)
{
    Console.WriteLine(employee.Name);
}
</code></pre>
<p>In the above code, the <strong>LINQ method syntax</strong> is used to filter the <strong>employees</strong> list and return a new list of employees who are working in the <strong>Software</strong> department. It uses a lambda expression as a predicate function. We then loop through the filtered results to print our results to the console.         </p>
<p>The complete code for various methods of filtering a list is provided below:</p>
<pre><code class="lang-program.cs">namespace Linq
{
    public class Employee
    {
        private string _name;
        private int _id;
        private string _department;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public string Department
        {
            get { return _department; }
            set { _department = value; }
        }
    }


    internal class Program
    {
        //GOAL: Our goal is to filter through the list to get the employees
        //that work in the software department.

        public static void ListOperations()
        {
           List&lt;Employee&gt; employees = new List&lt;Employee&gt;()
           {
            new Employee(){ Id=1, Name="John Doe", Department="Software"},
            new Employee(){ Id=2, Name="Angela Su", Department="Sales"},
            new Employee(){ Id=3, Name="Frank Kelvin", Department="Marketing"},
           new Employee(){ Id=4, Name="Joe Dustin", Department="Sales"},
           new Employee(){ Id=5, Name="Glory GG", Department="Software"},
           new Employee(){ Id=6, Name="Antonella Cruz", Department="Marketing"},
           new Employee(){ Id=5, Name="Andrew Logan", Department="Software"},
           new Employee(){ Id=6, Name="Billy Cruz", Department="Marketing"},
           new Employee(){ Id=5, Name="Sally Jane", Department="Software"},
           new Employee(){ Id=4, Name="Jon Snow", Department="Sales"},
           };


         //1: Iterative method
       Console.WriteLine("Filtering through the Employee list using the " +
                    "Iterative method");            
            foreach (var employee in employees)
            {
                if(employee.Department == "Software")
                {
                    Console.WriteLine(employee.Name);
                }
            }


       //2: LINQ query syntax (using the Where clause)            
          Console.WriteLine("\nWhere clause - LINQ query syntax ");
            var filteredResults = from employee in employees
                                  where employee.Department == "Software"
                                  select employee.Name;

            foreach(var result in filteredResults)
            {
                Console.WriteLine(result);
            }


       //3: LINQ method syntax (using the Where clause)            
         Console.WriteLine("\nWhere clause - LINQ method syntax ");
         var filteredResultsTwo = employees.Where(employee =&gt; employee.Department == "Software");
            foreach(var employee in filteredResultsTwo)
            {
                Console.WriteLine(employee.Name);
            }

        }

        static void Main(string[] args)
        {
            ListOperations();           
        }

    }
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Filtering allows you to select only those elements that meet a particular condition. In this article, we showed how to filter a list in C# using various methods.</p>
<p>I hope this article has given you enough information to filter the List collections easily. </p>
<p><strong>Happy coding!</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Remove an Item from a List in C# ]]>
                </title>
                <description>
                    <![CDATA[ While building your application in C#, you might need to store and manipulate sets of data. The List class is a member of the System.Collections.Generic namespace and you use it to store multiple objects of the same datatype. The List class represent... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-remove-an-item-from-a-list-in-c/</link>
                <guid isPermaLink="false">66c8c865073b3e2196fec37d</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Tue, 13 Dec 2022 00:28:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/bernd-dittrich-d_3EKbSg1tg-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>While building your application in C#, you might need to store and manipulate sets of data. The <strong>List</strong> class is a member of the <strong>System.Collections.Generic</strong> namespace and you use it to store multiple objects of the same datatype.</p>
<p>The <strong>List</strong> class represents a collection of strongly typed lists of objects that can be accessed using an index. Its class contains various methods to search, sort, and manipulate lists. </p>
<p>In this article, we are going to learn how to remove an item from a list in C#. There are different ways to remove an item from a list. Here you will learn how to remove an item from a <strong>List</strong> class using the <strong>Remove()</strong> and the <strong>RemoveAt()</strong> method.</p>
<h2 id="heading-how-to-remove-an-item-from-a-list-using-the-remove-method">How to Remove an Item From a List Using the Remove() Method</h2>
<p>Let’s assume you already have an existing list of strings of first names.</p>
<pre><code class="lang-program.cs">using System.Collections.Generic;

namespace Collections
{
    public class Program
    {
        static void Main(string[] args)
        {
            List&lt;string&gt; FirstName = new List&lt;string&gt;() { "John", "Jane", "Josh", "Debby", "Gilbert", "Joe" };
        }
    }
}
</code></pre>
<p>You use the <strong>Remove()</strong> method to remove the first occurrence of the item in a list. It takes in a parameter as an item and removes the first occurrence of the item.</p>
<p>Below is a code snippet showing how to use the <strong>Remove()</strong> method to remove an item from a list:</p>
<pre><code class="lang-program.cs">using System.Collections.Generic;

namespace Collections
{
    public class Program
    {
        static void Main(string[] args)
        {
            List&lt;string&gt; FirstName = new List&lt;string&gt;() { "John", "Jane", "Josh", "Debby", "Gilbert", "Joe" };

            //Iterating through the list before calling the Remove() method
            foreach(string names in FirstName)
            {
                Console.WriteLine(names);                
            }

            //Remove method
            FirstName.Remove("John");            

            //Iterating through the list after calling the Remove() method
            foreach (string names in FirstName)
            {
                Console.WriteLine(names);
            }
        }
    }
}
</code></pre>
<p>In the code above, <strong>FirstName.Remove(“John”)</strong> removes the first item with the value <strong>“John”</strong>. We then looped through the list to see the content of our list before and after manipulation.</p>
<h2 id="heading-how-to-remove-an-item-from-a-list-using-the-removeat-method">How to Remove an Item From a List Using the RemoveAt() Method</h2>
<p>Using the list we created, the <strong>RemoveAt()</strong> method takes an index as a parameter and removes the item at that index. Below is a code snippet showing how to use the <strong>Remove()</strong> method to remove an item from a list.</p>
<pre><code class="lang-program.cs">using System.Collections.Generic;

namespace Collections
{
    public class Program
    {
        static void Main(string[] args)
        {
            List&lt;string&gt; FirstName = new List&lt;string&gt;() { "John", "Jane", "Josh", "Debby", "Gilbert", "Joe" };

            //Iterating through the list before calling the RemoveAt() method
            foreach(string names in FirstName)
            {
                Console.WriteLine(names);                
            }

            //RemoveAt() method
            FirstName.RemoveAt(1);            

            //Iterating through the list after calling the RemoveAt() method
            foreach (string names in FirstName)
            {
                Console.WriteLine(names);
            }
        }
    }
}
</code></pre>
<p>In the code above, <strong>FirstName.RemoveAt(1)</strong> removes the item at index 1. It is necessary to know that the <strong>RemoveAt()</strong> method takes a zero-based index number (this means the positions/index starts at 0, not 1). We then looped through the list to see the content of our list before and after the list manipulation.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we discussed how to remove an item from a <strong>List</strong> class in C#. We also demonstrated two approaches with examples.  </p>
<p>I hope this article was helpful. <strong>Happy coding!</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Inheritance Works in C# – with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Inheritance is a branch of object-oriented programming that helps you write reusable code. It allows you to extend the content of a class to another class.  Other pillars of object-oriented programming include encapsulation, polymorphism, and abstrac... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/inheritance-in-c-sharp/</link>
                <guid isPermaLink="false">66c8c86e58265ae76d481676</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Tue, 29 Nov 2022 20:04:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/caspar-camille-rubin-fPkvU7RDmCo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Inheritance is a branch of object-oriented programming that helps you write reusable code. It allows you to extend the content of a class to another class. </p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/four-pillars-of-object-oriented-programming/">Other pillars of object-oriented programming</a> include encapsulation, polymorphism, and abstraction. </p>
<p>In this article, we will learn about inheritance in C# and the various types of inheritance we have in OOP.</p>
<h2 id="heading-what-is-inheritance">What is Inheritance?</h2>
<p>Inheritance is one of the key features of object-oriented programming (OOP). It is simply the process by which one class (the child or derived class) acquires the properties, methods, and fields of another class (the base, parent, or super class).</p>
<p>Inheritance in object-oriented programming means that you're creating classes that can pass down their properties to other classes without having to explicitly define the properties in new classes. </p>
<p>Inheritance does not only ensure the reusability of the codebase, but it also reduces your code’s complexity.</p>
<h2 id="heading-types-of-inheritance-in-c">Types of Inheritance in C</h2>
<p>Inheritance allows you to build families of related classes. The base/parent class defines the common data for the child class to inherit it. You use the colon operator (:) to show inheritance between two classes.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> System;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-comment">//...</span>
    }
    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span>:<span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-comment">//..</span>
    }
}
</code></pre>
<p>There are different types of inheritance in C#. We'll discuss them now.</p>
<h3 id="heading-single-inheritance-in-c">Single Inheritance in C</h3>
<p>Single inheritance usually occurs between two classes – the base class, and the derived class. It occurs when a class is inherited from a single-parent class. </p>
<p>Below is a code sample that shows single inheritance in C#:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> System;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> name;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id = <span class="hljs-number">9</span>;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayParentClassDetails</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"I am <span class="hljs-subst">{name}</span>"</span>);
            Console.WriteLine(<span class="hljs-string">$"ID : <span class="hljs-subst">{Id}</span>"</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getIdFromParentClass</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"This is my ID : <span class="hljs-subst">{Id}</span>"</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            <span class="hljs-comment">//accessing the inherited members from the child class</span>
            ChildClass child = <span class="hljs-keyword">new</span> ChildClass();
            child.getIdFromParentClass();
        }
    }
}
</code></pre>
<p>In the above code, we derived a subclass (ChildClass) from a super class (ParentClass). The ChildClass now has access to the fields and properties of the ParentClass through inheritance. We could easily access the inherited members from the ChildClass as seen above.</p>
<h3 id="heading-hierarchical-inheritance-in-c">Hierarchical Inheritance in C</h3>
<p>Hierarchical inheritance occurs when more than one derived class is created from a single-parent class.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> name;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id = <span class="hljs-number">9</span>;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayParentClassDetails</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"I am <span class="hljs-subst">{name}</span>"</span>);
            Console.WriteLine(<span class="hljs-string">$"ID : <span class="hljs-subst">{Id}</span>"</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getIdFromParentClass</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">"Displaying from my Child Class"</span>);
            Console.WriteLine(<span class="hljs-string">$"This is my ID : <span class="hljs-subst">{Id}</span>."</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">AnotherChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getIdFromParentClass</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">"Displaying from my other Child Class"</span>);
            Console.WriteLine(<span class="hljs-string">$"This is my ID : <span class="hljs-subst">{Id}</span>"</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            <span class="hljs-comment">//accessing the inherited members in the parent class (from the child class)</span>
            ChildClass child = <span class="hljs-keyword">new</span> ChildClass();
            child.getIdFromParentClass();

            <span class="hljs-comment">//accessing the inherited members in the parent class (from the other child class)</span>
            AnotherChildClass anotherChild = <span class="hljs-keyword">new</span> AnotherChildClass();
            anotherChild.getIdFromParentClass();
        }
    }
}
</code></pre>
<p>In the above code, we showed that we can derive more than one child class from a single parent class. </p>
<p>The ChildClass and AnotherChildClass both inherit the fields and methods of the base class, ParentClass. This is called Hierarchical inheritance. The two child classes can therefore access the fields and methods of the parent class.</p>
<h3 id="heading-multi-level-inheritance-in-c">Multi-level Inheritance in C</h3>
<p>Multi-level inheritance occurs when a class is derived from another derived class. It is simply a situation where a derived class is created and used as a base class for another class.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> name;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id = <span class="hljs-number">9</span>;

        <span class="hljs-comment">//...</span>
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-comment">//...</span>
        <span class="hljs-comment">//The Child class is the derived class in this case</span>
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ThirdClass</span> : <span class="hljs-title">ChildClass</span>
    {
        <span class="hljs-comment">//...</span>
        <span class="hljs-comment">//The ChildClass is the base class for the ThirdClass</span>
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            <span class="hljs-comment">//...</span>
        }
    }
}
</code></pre>
<p>In the above code, we also derived a subclass (ChildClass) from a super class (ParentClass). The ChildClass then acts as a base class for a sub-child class which was named ThirdClass.</p>
<h3 id="heading-multiple-inheritances-interfaces-in-c">Multiple Inheritances – Interfaces in C</h3>
<p>Multiple inheritances are not supported in C#. But you can achieve it by using <em>interfaces</em>. </p>
<p>Multiple inheritances allow a derived class to be inherited from multiple parent classes. You can see an example of how a child class can inherit from multiple interfaces that act like a parent class below:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{    
    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-keyword">interface</span> <span class="hljs-title">InterfaceA</span>
        {
            <span class="hljs-comment">//...</span>
        }

        <span class="hljs-keyword">interface</span> <span class="hljs-title">InterfaceB</span>
        {
            <span class="hljs-comment">//...</span>
        }     

        <span class="hljs-keyword">class</span> <span class="hljs-title">NewClass</span>: <span class="hljs-title">InterfaceA</span>, <span class="hljs-title">InterfaceB</span>
        {
            <span class="hljs-comment">//...            </span>
        }

        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            <span class="hljs-comment">//...</span>
        }
    }
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Inheritance is important because it helps keep your code clean. It makes it easier to build families of related classes. The child class can inherit all the fields, properties, and methods that are contained in the parent class except those classes that are declared as a private class. </p>
<p>Through this article, I hope you have gained some insight about inheritance in C#.</p>
<p>Happy Coding.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Firebase Authentication in a React App ]]>
                </title>
                <description>
                    <![CDATA[ Almost every web application requires some form of authentication. This prevents unauthorized users from having access to the app's inner workings.  In this tutorial, you will learn how to authenticate your React app with the Firebase SDK. How to Aut... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/use-firebase-authentication-in-a-react-app/</link>
                <guid isPermaLink="false">66c8c87b073b3e2196fec384</guid>
                
                    <category>
                        <![CDATA[ authentication ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Firebase ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Mon, 31 Oct 2022 14:54:20 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/ferenc-almasi-tvHtIGbbjMo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Almost every web application requires some form of authentication. This prevents unauthorized users from having access to the app's inner workings. </p>
<p>In this tutorial, you will learn how to authenticate your React app with the Firebase SDK.</p>
<h2 id="heading-how-to-authenticate-with-firebase">How to Authenticate with Firebase</h2>
<p>Authenticating with Firebase makes things easy for both end users and developers. Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries. This allows you to focus on your users, not complex infrastructure to support them. </p>
<p>Firebase supports a lot of ways for users to get authenticated. They include authentication through email addresses, third-party providers such as Twitter, Facebook, Github, Google, Microsoft, and much more.</p>
<h2 id="heading-how-to-set-up-firebase-authentication">How to Set Up Firebase Authentication</h2>
<p>Before you set up and initialize the Firebase SDK for your React app, you'll need to sign up for Firebase using your Google account. </p>
<p>If you have a Firebase account already, sign in and follow the prompts to create a new project. Pick a suitable name for your project and click <strong>Continue.</strong></p>
<p>For this tutorial, we will name our project <strong>Focus-app.</strong> Your next screen will be a prompt to enable Google Analytics. We won’t be needing it. You can choose to turn it off.</p>
<p>Congratulations, you have successfully set up your Firebase Console. Your next screen will be the Firebase console dashboard which will look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screenshot--197-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>There are a lot of ways to authenticate users using Firebase. For this tutorial, we will authenticate our users with their email addresses and passwords. </p>
<p>To start using the Firebase SDK Authentication, select the Authentication SDK among the <strong>Build</strong> categories. </p>
<p>Next, we will set up our sign-in method. Click on <strong>Set up sign-in method</strong> and select <strong>Email/Password</strong> from the list of sign-in providers.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screenshot--209--3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Enable the <strong>Email/Password</strong> option to let users sign up using their email address and password and click on <strong>Save</strong>.</p>
<h2 id="heading-how-to-set-up-your-react-app-with-react-router">How to Set Up Your React App with React Router</h2>
<p>Authentication is a feature that most apps need. We will set up our React app by using the following command:</p>
<pre><code class="lang-js">$ npx create-react-app focus-app
</code></pre>
<p>Before we start our app, we should set up our react-router-dom. You can install your <strong>react-router-dom</strong> by running the following command:</p>
<pre><code class="lang-js">$ npm i -D react-router-dom
</code></pre>
<p>To set up your React app to use <strong>react-router-dom</strong>, you can read their <a target="_blank" href="https://reactrouter.com/en/6.4.2/start/tutorial">docs</a>. After setting up your routes, your app.js file should have the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, {useState, useEffect} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> Home <span class="hljs-keyword">from</span> <span class="hljs-string">'./page/Home'</span>;
<span class="hljs-keyword">import</span> Signup <span class="hljs-keyword">from</span> <span class="hljs-string">'./page/Signup'</span>;
<span class="hljs-keyword">import</span> Login <span class="hljs-keyword">from</span> <span class="hljs-string">'./page/Login'</span>;
<span class="hljs-keyword">import</span> { BrowserRouter <span class="hljs-keyword">as</span> Router} <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>;
<span class="hljs-keyword">import</span> {Routes, Route} <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Router</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>                              
            <span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span>                                                                        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Home</span>/&gt;</span>}/&gt;
               <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/signup"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Signup</span>/&gt;</span>}/&gt;
               <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/login"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Login</span>/&gt;</span>}/&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">Routes</span>&gt;</span>                    
        <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Router</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>We set up our React app to have three routes: <strong>Home</strong>, <strong>Login</strong>, and the <strong>Signup</strong> page.</p>
<h2 id="heading-how-to-set-up-and-configure-firebase-sdk">How to Set Up and Configure Firebase SDK</h2>
<p>You have two options to set up your Firebase SDK. We will be installing and setting up Firebase using the <strong>npm</strong> option. </p>
<p>Before installing the Firebase SDK, you should have <a target="_blank" href="https://nodejs.org/en/download/">npm</a> installed on your machine. You can install the latest Firebase SDK by running the following command:</p>
<pre><code class="lang-js">$ npm install firebase
</code></pre>
<p>To initialize Firebase, create a <strong>firebase.js</strong> file in your <strong>src</strong> directory. Get your Firebase configuration in the project settings part of your dashboard and copy your Firebase configuration into your <strong>firebase.js</strong> file. Your <strong>firebase.js</strong> file should have the following code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Import the functions you need from the SDKs you need</span>
<span class="hljs-keyword">import</span> { initializeApp } <span class="hljs-keyword">from</span> <span class="hljs-string">"firebase/app"</span>;
<span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> Add SDKs for Firebase products that you want to use</span>
<span class="hljs-comment">// https://firebase.google.com/docs/web/setup#available-libraries</span>
<span class="hljs-comment">// Your web app's Firebase configuration</span>

<span class="hljs-keyword">const</span> firebaseConfig = {
  <span class="hljs-attr">apiKey</span>: <span class="hljs-string">"XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"</span>,
  <span class="hljs-attr">authDomain</span>: <span class="hljs-string">"XXXXXXXXXXXXXXXXXXXXXXXX"</span>,
  <span class="hljs-attr">projectId</span>: <span class="hljs-string">"XXXXXXXXX"</span>,
  <span class="hljs-attr">storageBucket</span>: <span class="hljs-string">"XXXXXXXXXXXXXXXXXX"</span>,
  <span class="hljs-attr">messagingSenderId</span>: <span class="hljs-string">"XXXXXXXXXXXX"</span>,
  <span class="hljs-attr">appId</span>: <span class="hljs-string">"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"</span>
};

<span class="hljs-comment">// Initialize Firebase</span>
<span class="hljs-keyword">const</span> app = initializeApp(firebaseConfig);
</code></pre>
<p>Congratulations, you have successfully initialized Firebase. </p>
<p>To start using the Firebase SDK, you will have to import the products you'd like to use. After importing the Firebase SDK for authentication, your <strong>firebase.js</strong> file should have the following code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Import the functions you need from the SDKs you need</span>
<span class="hljs-keyword">import</span> { initializeApp } <span class="hljs-keyword">from</span> <span class="hljs-string">"firebase/app"</span>;
<span class="hljs-keyword">import</span> { getAuth } <span class="hljs-keyword">from</span> <span class="hljs-string">"firebase/auth"</span>;

<span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> Add SDKs for Firebase products that you want to use</span>
<span class="hljs-comment">// https://firebase.google.com/docs/web/setup#available-libraries</span>
<span class="hljs-comment">// Your web app's Firebase configuration</span>

<span class="hljs-keyword">const</span> firebaseConfig = {
  <span class="hljs-attr">apiKey</span>: <span class="hljs-string">"AIzaSyAAx_knJ_qqxPkJQ_xoIZnxt_c6gb6Wdys"</span>,
  <span class="hljs-attr">authDomain</span>: <span class="hljs-string">"todoapp-eeeb7.firebaseapp.com"</span>,
  <span class="hljs-attr">projectId</span>: <span class="hljs-string">"todoapp-eeeb7"</span>,
  <span class="hljs-attr">storageBucket</span>: <span class="hljs-string">"todoapp-eeeb7.appspot.com"</span>,
  <span class="hljs-attr">messagingSenderId</span>: <span class="hljs-string">"1072574112522"</span>,
  <span class="hljs-attr">appId</span>: <span class="hljs-string">"1:1072574112522:web:65fc4e184aed9894dc90f3"</span>
};

<span class="hljs-comment">// Initialize Firebase</span>
<span class="hljs-keyword">const</span> app = initializeApp(firebaseConfig);

<span class="hljs-comment">// Initialize Firebase Authentication and get a reference to the service</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> auth = getAuth(app);
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> app;
</code></pre>
<h2 id="heading-how-to-authenticate-your-react-app">How to Authenticate Your React App</h2>
<p>Firebase has a number of built-in products, one of which is authentication. According to its <a target="_blank" href="https://firebase.google.com/docs/auth">docs</a>, </p>
<blockquote>
<p>to authenticate users to your app, Firebase Authentication provides cool features like backend services, easy-to-use SDKs, and ready-made UI libraries. </p>
</blockquote>
<p>Firebase Authentication allows users to sign in to your app using different sign-in methods. In this tutorial, we will learn how to authenticate users using email and passwords to sign in to your app. We won’t be using any styling for this article.</p>
<p>To create a user, you should create a form that takes inputs and create new users using the <strong>createUserWithEmailAndPassword</strong> method from Firebase. </p>
<p>The form should take the new user's email address and password as input and pass them into the <strong>createUserWithEmailAndPassword</strong> method. If a user is successfully created, you will be routed to the login screen. </p>
<p>Here is the complete code to create a user:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, {useState} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { NavLink, useNavigate } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>;
<span class="hljs-keyword">import</span> {  createUserWithEmailAndPassword  } <span class="hljs-keyword">from</span> <span class="hljs-string">'firebase/auth'</span>;
<span class="hljs-keyword">import</span> { auth } <span class="hljs-keyword">from</span> <span class="hljs-string">'../firebase'</span>;

<span class="hljs-keyword">const</span> Signup = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> navigate = useNavigate();

    <span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">''</span>)
    <span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">''</span>);

    <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-keyword">async</span> (e) =&gt; {
      e.preventDefault()

      <span class="hljs-keyword">await</span> createUserWithEmailAndPassword(auth, email, password)
        .then(<span class="hljs-function">(<span class="hljs-params">userCredential</span>) =&gt;</span> {
            <span class="hljs-comment">// Signed in</span>
            <span class="hljs-keyword">const</span> user = userCredential.user;
            <span class="hljs-built_in">console</span>.log(user);
            navigate(<span class="hljs-string">"/login"</span>)
            <span class="hljs-comment">// ...</span>
        })
        .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
            <span class="hljs-keyword">const</span> errorCode = error.code;
            <span class="hljs-keyword">const</span> errorMessage = error.message;
            <span class="hljs-built_in">console</span>.log(errorCode, errorMessage);
            <span class="hljs-comment">// ..</span>
        });


    }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">main</span> &gt;</span>        
        <span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>                  
                    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> FocusApp <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>                                                                            
                    <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>                                                                                            
                        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"email-address"</span>&gt;</span>
                                Email address
                            <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                                <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span>
                                <span class="hljs-attr">label</span>=<span class="hljs-string">"Email address"</span>
                                <span class="hljs-attr">value</span>=<span class="hljs-string">{email}</span>
                                <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setEmail(e.target.value)}  
                                required                                    
                                placeholder="Email address"                                
                            /&gt;
                        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"password"</span>&gt;</span>
                                Password
                            <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                                <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
                                <span class="hljs-attr">label</span>=<span class="hljs-string">"Create password"</span>
                                <span class="hljs-attr">value</span>=<span class="hljs-string">{password}</span>
                                <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setPassword(e.target.value)} 
                                required                                 
                                placeholder="Password"              
                            /&gt;
                        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>                                             

                        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
                            <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> 
                            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onSubmit}</span>                        
                        &gt;</span>  
                            Sign up                                
                        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

                    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
                        Already have an account?{' '}
                        <span class="hljs-tag">&lt;<span class="hljs-name">NavLink</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/login"</span> &gt;</span>
                            Sign in
                        <span class="hljs-tag">&lt;/<span class="hljs-name">NavLink</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>                   
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Signup
</code></pre>
<p>Firebase allows existing users to sign in using the <strong>email</strong> and <strong>password</strong> that they initially used for signup. </p>
<p>To allow existing users to sign in, you should create a form that collects both their email and password. The form has a submit button that calls the <strong>signInWithEmailAndPassword</strong> method whenever it is clicked. </p>
<p>You can sign in using the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, {useState} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> {  signInWithEmailAndPassword   } <span class="hljs-keyword">from</span> <span class="hljs-string">'firebase/auth'</span>;
<span class="hljs-keyword">import</span> { auth } <span class="hljs-keyword">from</span> <span class="hljs-string">'../firebase'</span>;
<span class="hljs-keyword">import</span> { NavLink, useNavigate } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>

<span class="hljs-keyword">const</span> Login = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> navigate = useNavigate();
    <span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">''</span>);
    <span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">''</span>);

    <span class="hljs-keyword">const</span> onLogin = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
        e.preventDefault();
        signInWithEmailAndPassword(auth, email, password)
        .then(<span class="hljs-function">(<span class="hljs-params">userCredential</span>) =&gt;</span> {
            <span class="hljs-comment">// Signed in</span>
            <span class="hljs-keyword">const</span> user = userCredential.user;
            navigate(<span class="hljs-string">"/home"</span>)
            <span class="hljs-built_in">console</span>.log(user);
        })
        .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
            <span class="hljs-keyword">const</span> errorCode = error.code;
            <span class="hljs-keyword">const</span> errorMessage = error.message;
            <span class="hljs-built_in">console</span>.log(errorCode, errorMessage)
        });

    }

    <span class="hljs-keyword">return</span>(
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">main</span> &gt;</span>        
                <span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>                                            
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> FocusApp <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>                       

                        <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>                                              
                            <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"email-address"</span>&gt;</span>
                                    Email address
                                <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                                    <span class="hljs-attr">id</span>=<span class="hljs-string">"email-address"</span>
                                    <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span>
                                    <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span>                                    
                                    <span class="hljs-attr">required</span>                                                                                
                                    <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email address"</span>
                                    <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span>=&gt;</span>setEmail(e.target.value)}
                                /&gt;
                            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                            <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"password"</span>&gt;</span>
                                    Password
                                <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                                    <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span>
                                    <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
                                    <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>                                    
                                    <span class="hljs-attr">required</span>                                                                                
                                    <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span>
                                    <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span>=&gt;</span>setPassword(e.target.value)}
                                /&gt;
                            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                            <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">button</span>                                    
                                    <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onLogin}</span>                                        
                                &gt;</span>      
                                    Login                                                                  
                                <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>                               
                        <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-sm text-white text-center"</span>&gt;</span>
                            No account yet? {' '}
                            <span class="hljs-tag">&lt;<span class="hljs-name">NavLink</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/signup"</span>&gt;</span>
                                Sign up
                            <span class="hljs-tag">&lt;/<span class="hljs-name">NavLink</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
        <span class="hljs-tag">&lt;/&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Login
</code></pre>
<p>Firebase Authentication provides other sign-in methods, including using GitHub, Microsoft, Apple, or a federated identity provider, such as <a target="_blank" href="https://firebase.google.com/docs/auth/web/google-signin">Google Sign-In</a> or <a target="_blank" href="https://firebase.google.com/docs/auth/web/facebook-login">Facebook Login</a>. </p>
<p>After a successful sign-in, a user’s information can be accessed and can be used to add more features to your app, including protecting your routes.</p>
<p>To get a currently signed-up user, we set an observer on the Auth object. We can get a currently signed user using the following code in the <strong>Home</strong> component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { onAuthStateChanged } <span class="hljs-keyword">from</span> <span class="hljs-string">"firebase/auth"</span>;
<span class="hljs-keyword">import</span> { auth } <span class="hljs-keyword">from</span> <span class="hljs-string">'../firebase'</span>;

<span class="hljs-keyword">const</span> Home = <span class="hljs-function">() =&gt;</span> {

    useEffect(<span class="hljs-function">()=&gt;</span>{
        onAuthStateChanged(auth, <span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> {
            <span class="hljs-keyword">if</span> (user) {
              <span class="hljs-comment">// User is signed in, see docs for a list of available properties</span>
              <span class="hljs-comment">// https://firebase.google.com/docs/reference/js/firebase.User</span>
              <span class="hljs-keyword">const</span> uid = user.uid;
              <span class="hljs-comment">// ...</span>
              <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"uid"</span>, uid)
            } <span class="hljs-keyword">else</span> {
              <span class="hljs-comment">// User is signed out</span>
              <span class="hljs-comment">// ...</span>
              <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"user is logged out"</span>)
            }
          });

    }, [])

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>        
      …
    <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home
</code></pre>
<p>To complete our Firebase authentication, after creating a user and signing in, there should be a way to sign out users. </p>
<p>To sign out a user, the <strong>signOut</strong> method is called from Firebase. After signing in to the <strong>Home</strong> route, there will be a button to sign out whenever the <strong>Logout</strong> button is clicked. The button should have an <strong>onClick</strong> event that calls the <strong>signOut</strong> method from Firebase auth. A success message will be displayed on the console if the sign out is successful. </p>
<p>Here is the complete code to sign out a user:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> {  signOut } <span class="hljs-keyword">from</span> <span class="hljs-string">"firebase/auth"</span>;
<span class="hljs-keyword">import</span> {auth} <span class="hljs-keyword">from</span> <span class="hljs-string">'../../firebase'</span>;
<span class="hljs-keyword">import</span> { useNavigate } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>;

<span class="hljs-keyword">const</span> Home = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> navigate = useNavigate();

    <span class="hljs-keyword">const</span> handleLogout = <span class="hljs-function">() =&gt;</span> {               
        signOut(auth).then(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-comment">// Sign-out successful.</span>
            navigate(<span class="hljs-string">"/"</span>);
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Signed out successfully"</span>)
        }).catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        <span class="hljs-comment">// An error happened.</span>
        });
    }

    <span class="hljs-keyword">return</span>(
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
                    Welcome Home
                <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

                <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleLogout}</span>&gt;</span>
                        Logout
                    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
        <span class="hljs-tag">&lt;/&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Firebase authentication allows you to create the identity of a user. It authenticates users seamlessly. </p>
<p>Through this article, I hope you have got enough knowledge to build applications that authenticate users. You can check the <a target="_blank" href="https://firebase.google.com/docs/auth">documentation</a> to learn more.</p>
<p>Here is a <a target="_blank" href="https://github.com/IsraelChidera/focus-app">link</a> to the GitHub repository that uses Firebase authentication. It also uses <strong>TailwindCSS</strong> for styling and <strong>React Router</strong> for routing.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Cloud Firestore in a React App ]]>
                </title>
                <description>
                    <![CDATA[ Firebase provides some great services like NoSQL databases, authentication, cloud storage, and much more. In this tutorial, we will learn how to use your React application to read and add data to your Firebase database.  To demonstrate this, we will ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-the-firebase-database-in-react/</link>
                <guid isPermaLink="false">66c8c86b073b3e2196fec382</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Firebase ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Mon, 24 Oct 2022 15:08:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/lautaro-andreani-xkBaqlcqeb4-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Firebase provides some great services like NoSQL databases, authentication, cloud storage, and much more.</p>
<p>In this tutorial, we will learn how to use your React application to read and add data to your Firebase database. </p>
<p>To demonstrate this, we will learn how to build a Todo app using React and Cloud Firestore (Firebase9 web SDK). Before we start building, let's understand the tools we will use for this tutorial.</p>
<h2 id="heading-what-is-cloud-firestore">What is Cloud Firestore?</h2>
<p>Unlike some databases that store data in tables (SQL databases), Cloud Firestore is a non-tabular database that stores data in collections. </p>
<p>According to the <a target="_blank" href="https://firebase.google.com/docs/firestore">docs</a>, </p>
<blockquote>
<p>"Cloud Firestore is a flexible, scalable database for mobile, web, and server development. Cloud Firestore does not require you to explicitly create collections or documents. Cloud Firestore stores data in documents, which are stored in collections."</p>
</blockquote>
<p>Since we won't focus on the design part in this tutorial, I'll provide the CSS styling. Let's go ahead and set up our database.</p>
<h2 id="heading-how-to-set-up-your-cloud-firestore">How to Set Up Your Cloud Firestore</h2>
<p>Before you set up Cloud Firestore, you'll need to sign into your Firebase console. Here’s how.</p>
<h3 id="heading-sign-into-firebase">Sign into Firebase</h3>
<p>Go to <a target="_blank" href="https://console.firebase.google.com/">Firebase Console</a> and sign in with your Google account. If you don’t have an account yet, sign up with your Google account and follow the prompts to create a new project.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/1-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>firebase console</em></p>
<p>Pick a suitable name for your project and click <strong>continue</strong>. For this tutorial, we will name our project <strong>Todo-app</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/2-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>setting up firebase</em></p>
<p>Your next screen is a prompt to enable <strong>Google Analytics</strong>. You can choose to turn it off. We won’t be needing Google Analytics for this tutorial, so I will turn it off.</p>
<p>Congratulations, you have successfully set up your Cloud Firestore. Your next screen will be the Firebase console dashboard.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/3-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>firebase dashboard</em></p>
<h2 id="heading-how-to-set-up-a-react-app-for-firebase">How to Set Up a React App for Firebase</h2>
<p>We will be creating a new React app using <strong>npx</strong>. We will create a new React app with <strong>firebase-react-app</strong> as the app name and also the directory’s name. Using the command line, enter the following code to create a new React app:</p>
<pre><code>$ npx create-react-app firebase-react-app
</code></pre><p>To start your React app, use the following commands. It opens your React app in Visual Studio Code, navigates into your new directory, and finally runs your React app.</p>
<pre><code>$ code .
$ cd firebase-storage
$ npm run start
</code></pre><p>There are a bunch of starter files and code we won’t be needing for this tutorial. We will delete the <strong>App.test.js</strong>, <strong>index.css</strong>, and <strong>logo.svg</strong> files. We'll also delete the starter code in the <strong>App.css</strong> and <strong>App.js</strong> files.</p>
<h2 id="heading-overview-of-the-firebase-console">Overview of the Firebase Console</h2>
<p>The Firebase dashboard has a <strong>sidebar</strong> and a <strong>main</strong> view. The sidebar has been categorized into different products that Firebase offers. Apart from our area of interest, Cloud Firestore, Firebase has a lot of products with awesome services for authentication, storage, databases, and more.  </p>
<p>To start using the Cloud Firestore services, navigate to your Firebase dashboard, click on the <strong>Build</strong> dropdown, and select <strong>Firestore Database</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/Screenshot--193-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Firebase dashboard showing the cloud firestore view</em></p>
<p>Select the option to <strong>create a database</strong> and set the security rules to start in <strong>test mode</strong>. Select the default Firestore location and click to <strong>enable your database</strong>.</p>
<p>Continue configuring your Firebase by adding the Firebase web SDK to our React app. To do this, click on the web icon on your project overview screen.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/3-3.png" alt="Image" width="600" height="400" loading="lazy">
<em>Click the web icon</em></p>
<p>Your next prompt will require you to add Firebase to your web app. You'll need to choose a <strong>nickname</strong> for your app. We will be using <strong>Todo-app</strong> as the nickname for our app. </p>
<p>We won’t be needing Firebase hosting. So, you can leave the box for Firebase hosting unchecked. Then, click on <strong>register app.</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/4-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Firebase screen to register your web app</em></p>
<p>Your next prompt will require you to install Firebase's latest SDK using <a target="_blank" href="https://www.npmjs.com/">npm</a> and will also provide your web app configuration.</p>
<pre><code>$ npm install firebase
</code></pre><p>Click on <strong>Continue to Console</strong>. You are halfway to adding Firebase to your React app.</p>
<p>Your web app configuration will be displayed with your unique API keys and some other useful information. </p>
<p>Create a file named <strong>firebase.js</strong> in the <strong>src</strong> directory and paste your Firebase configuration in the <strong>firebase.js</strong> file. We will also import the Cloud Firestore SDK into our React app. Here is how your <strong>firebase.js</strong> should look like:</p>
<pre><code class="lang-js"> <span class="hljs-comment">// Import the functions you need from the SDKs you need</span>
<span class="hljs-keyword">import</span> { initializeApp } <span class="hljs-keyword">from</span> <span class="hljs-string">"firebase/app"</span>;
<span class="hljs-keyword">import</span> { getFirestore } <span class="hljs-keyword">from</span> <span class="hljs-string">"firebase/firestore"</span>;
<span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> Add SDKs for Firebase products that you want to use</span>
<span class="hljs-comment">// https://firebase.google.com/docs/web/setup#available-libraries</span>
<span class="hljs-comment">// Your web app's Firebase configuration</span>
<span class="hljs-keyword">const</span> firebaseConfig = {
  <span class="hljs-attr">apiKey</span>: <span class="hljs-string">"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"</span>,
  <span class="hljs-attr">authDomain</span>: <span class="hljs-string">"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"</span>,
  <span class="hljs-attr">projectId</span>: <span class="hljs-string">"XXXXXXXXXXXXXXXXX"</span>,
  <span class="hljs-attr">storageBucket</span>: <span class="hljs-string">"XXXXXXXXXXXXXXXXXXXXXXXX"</span>,

  <span class="hljs-attr">messagingSenderId</span>: <span class="hljs-string">"XXXXXXXXXXXXXXX"</span>,
  <span class="hljs-attr">appId</span>: <span class="hljs-string">"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"</span>
};
<span class="hljs-comment">// Initialize Firebase</span>

<span class="hljs-keyword">const</span> app = initializeApp(firebaseConfig);
<span class="hljs-comment">// Export firestore database</span>
<span class="hljs-comment">// It will be imported into your react app whenever it is needed</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> db = getFirestore(app);
</code></pre>
<p>Congratulations again. You have successfully initialized Firebase and Cloud Firestore, and exported them so that you can use them in your React app.</p>
<h2 id="heading-how-to-create-our-application">How to Create Our Application</h2>
<p>For the sake of writing cleaner code, we’ll create a <strong>components</strong> folder inside our <strong>src</strong> directory. We will then create a <strong>Todo.js</strong> file inside our <strong>components</strong> folder. This new file will be imported into the <strong>App.js</strong> file so as to be rendered.</p>
<p>The <strong>Todo.js</strong> file will have the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"../App.css"</span>;

<span class="hljs-keyword">const</span> Todo = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [todo, setTodo] = useState(<span class="hljs-string">""</span>)

    <span class="hljs-keyword">const</span> addTodo = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
        e.preventDefault();        
    }

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">section</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"todo-container"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"todo"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"header"</span>&gt;</span>
                    Todo-App
                <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

                <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                            <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
                            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"What do you have to do today?"</span>
                            <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span>=&gt;</span>setTodo(e.target.value)}
                        /&gt;
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"btn-container"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
                            <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>
                            <span class="hljs-attr">className</span>=<span class="hljs-string">"btn"</span>
                            <span class="hljs-attr">onClick</span>=<span class="hljs-string">{addTodo}</span>
                        &gt;</span>
                            Submit
                        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"todo-content"</span>&gt;</span>
                    ...
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span></span>
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Todo
</code></pre>
<h3 id="heading-code-explanation">Code explanation:</h3>
<p>The <strong>Todo.js</strong> file has an input tag (to take the user’s input), a button with an <strong>onClick</strong> function (we will be using that to post data to our Firestore), and an <strong>onChange</strong> function that handles the states. </p>
<p>We won't be going deep into handling form input. The above code shows how to do so with the <strong>useState</strong> hook. </p>
<p>Whenever the button is clicked, the value of the input, which will be handled by the useState hooks, will be added to the Cloud Firestore.</p>
<p>Like I mentioned above, this is not a CSS tutorial. So here is the code for the CSS styling that you can copy and paste in:</p>
<pre><code class="lang-css">*{
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">box-sizing</span>: border-box;
}
<span class="hljs-selector-class">.todo-container</span> {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">justify-content</span>: center;
    <span class="hljs-attribute">align-items</span>: center;    
}

<span class="hljs-selector-class">.todo</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">70%</span>;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">3rem</span> auto <span class="hljs-number">0</span> auto;    
}

<span class="hljs-selector-class">.header</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2.5rem</span>;
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">1rem</span>;
    <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-tag">input</span> {
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">3px</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}

<span class="hljs-selector-class">.btn-container</span> {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">justify-content</span>: center;
    <span class="hljs-attribute">align-items</span>: center;
    <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">1rem</span>;
}

<span class="hljs-selector-class">.btn</span> {
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">1rem</span>;
    <span class="hljs-attribute">background</span>: <span class="hljs-number">#334</span>;
    <span class="hljs-attribute">color</span>: white;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
    <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-class">.todo-content</span> {
    <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">2rem</span>;
}
</code></pre>
<h2 id="heading-how-to-add-data-to-cloud-firestore">How to Add Data to Cloud Firestore</h2>
<p>You can add data gotten from the input to the Cloud Firestore using the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { collection, addDoc } <span class="hljs-keyword">from</span> <span class="hljs-string">"firebase/firestore"</span>;
<span class="hljs-keyword">import</span> {db} <span class="hljs-keyword">from</span> <span class="hljs-string">'../firebase'</span>;

    <span class="hljs-keyword">const</span> addTodo = <span class="hljs-keyword">async</span> (e) =&gt; {
        e.preventDefault();  

        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">const</span> docRef = <span class="hljs-keyword">await</span> addDoc(collection(db, <span class="hljs-string">"todos"</span>), {
              <span class="hljs-attr">todo</span>: todo,    
            });
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Document written with ID: "</span>, docRef.id);
          } <span class="hljs-keyword">catch</span> (e) {
            <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error adding document: "</span>, e);
          }
    }
</code></pre>
<h3 id="heading-code-explanation-1">Code explanation:</h3>
<p>In Cloud Firestore, data is stored in collections. To add data to Firestore, import the <strong>Collection</strong> and <strong>addDoc</strong> functions. We also import the <strong>db</strong> initialized in the <strong>firebase.js</strong> file. </p>
<p>When the button is clicked, the Cloud Firestore creates a collection (we have named <strong>todos)</strong> and adds data as a document to the <strong>todos</strong> collection.  </p>
<p>Congratulations if you are still following. You have successfully added your data to Firebase.</p>
<h2 id="heading-how-to-read-data">How to Read Data</h2>
<p>You can always check your Firebase console dashboard to see all the data you have added. </p>
<p>To fetch data added to your Firestore, we will use the Firebase <strong>get</strong> method to read all documents added to a collection. You can add read data added to the Cloud Firestore using the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { collection, getDocs } <span class="hljs-keyword">from</span> <span class="hljs-string">"firebase/firestore"</span>;
<span class="hljs-keyword">import</span> {db} <span class="hljs-keyword">from</span> <span class="hljs-string">'../firebase'</span>;
Import { useState } <span class="hljs-keyword">from</span> ‘react’;

   <span class="hljs-keyword">const</span> [todos, setTodos] = useState([]);

    <span class="hljs-keyword">const</span> fetchPost = <span class="hljs-keyword">async</span> () =&gt; {

        <span class="hljs-keyword">await</span> getDocs(collection(db, <span class="hljs-string">"todos"</span>))
            .then(<span class="hljs-function">(<span class="hljs-params">querySnapshot</span>)=&gt;</span>{               
                <span class="hljs-keyword">const</span> newData = querySnapshot.docs
                    .map(<span class="hljs-function">(<span class="hljs-params">doc</span>) =&gt;</span> ({...doc.data(), <span class="hljs-attr">id</span>:doc.id }));
                setTodos(newData);                
                <span class="hljs-built_in">console</span>.log(todos, newData);
            })

    }

    useEffect(<span class="hljs-function">()=&gt;</span>{
        fetchPost();
    }, [])
</code></pre>
<h3 id="heading-code-explanation-2">Code explanation:</h3>
<p>We imported the <strong>collection</strong> and <strong>getDocs</strong> functions from Firebase. We used the <strong>getDocs</strong> function to get data from the collection we initially created. We used the <strong>useEffect</strong> hook to fetch data after each re-rendering. We used the <strong>useState</strong> hook to handle the data gotten from Firestore. We mapped through each document in the <strong>Todos</strong> collection and added each value to the <strong>setTodos</strong> array. </p>
<p>The <strong>todo</strong> array now has all the data we added to the Firestore. We can read each todo input we added to the Firestore database by using the following code:</p>
<pre><code class="lang-js">&lt;div className=<span class="hljs-string">"todo-content"</span>&gt;
    {
        todos?.map(<span class="hljs-function">(<span class="hljs-params">todo,i</span>)=&gt;</span>(
            <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{i}</span>&gt;</span>
                {todo.todo}
            <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
        ))
    }
&lt;/div&gt;
</code></pre>
<p>If you are still following up to this point, congratulations. You have successfully added and read data from the Cloud Firestore using React.js. Below is the complete code of our Todo.js file:</p>
<pre><code class="lang-todo.js">import "../App.css";
import React, { useState, useEffect } from 'react';
import { collection, addDoc, getDocs } from "firebase/firestore";


const Todo = () =&gt; {
    const [todo, setTodo] = useState("");
    const [todos, setTodos] = useState([]);

    const addTodo = async (e) =&gt; {
        e.preventDefault();  

        try {
            const docRef = await addDoc(collection(db, "todos"), {
              todo: todo,    
            });
            console.log("Document written with ID: ", docRef.id);
          } catch (e) {
            console.error("Error adding document: ", e);
          }
    }

    const fetchPost = async () =&gt; {

        await getDocs(collection(db, "todos"))
            .then((querySnapshot)=&gt;{              
                const newData = querySnapshot.docs
                    .map((doc) =&gt; ({...doc.data(), id:doc.id }));
                setTodos(newData);                
                console.log(todos, newData);
            })

    }

    useEffect(()=&gt;{
        fetchPost();
    }, [])


    return (
        &lt;section className="todo-container"&gt;
            &lt;div className="todo"&gt;
                &lt;h1 className="header"&gt;
                    Todo-App
                &lt;/h1&gt;

                &lt;div&gt;

                    &lt;div&gt;
                        &lt;input
                            type="text"
                            placeholder="What do you have to do today?"
                            onChange={(e)=&gt;setTodo(e.target.value)}
                        /&gt;
                    &lt;/div&gt;

                    &lt;div className="btn-container"&gt;
                        &lt;button
                            type="submit"
                            className="btn"
                            onClick={addTodo}
                        &gt;
                            Submit
                        &lt;/button&gt;
                    &lt;/div&gt;

                &lt;/div&gt;

                &lt;div className="todo-content"&gt;
                    {
                        todos?.map((todo,i)=&gt;(
                            &lt;p key={i}&gt;
                                {todo.todo}
                            &lt;/p&gt;
                        ))
                    }
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/section&gt;
    )
}

export default Todo
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you followed the instructions up to this point, you should be able to work with Cloud Firestore in your React app. </p>
<p>Cloud Firestore does more than add and fetch data. You can check the <a target="_blank" href="https://firebase.google.com/docs/firestore/quickstart">documentation</a> to learn more.</p>
<p>I hope you learnt a lot through this tutorial. Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Avoid Prop Drilling with the React Context API ]]>
                </title>
                <description>
                    <![CDATA[ The React Context API provides a way to pass data through multiple nested levels of components without having to manually pass that data to each level.  React context is one sure way of globally managing your data in your app, and it's a good way to ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/avoid-prop-drilling-with-react-context-api/</link>
                <guid isPermaLink="false">66c8c8550f021017a28a49c6</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Thu, 13 Oct 2022 16:52:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/ferenc-almasi-c8h0n7fSTqs-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The React Context API provides a way to pass data through multiple nested levels of components without having to manually pass that data to each level. </p>
<p>React context is one sure way of globally managing your data in your app, and it's a good way to avoid prop drilling. </p>
<p>In this tutorial, we will learn how to use the React context API (useContext hook) to avoid prop drilling.</p>
<h2 id="heading-what-is-prop-drilling">What is Prop Drilling?</h2>
<p>In a traditional React application, data is often shared between components using props. Manually sharing this data can be hectic, especially when shared between multiple nested components. Also, sharing data between two child components can be cumbersome. Hence the need for global state management. </p>
<p><strong>Prop drilling</strong> is a situation where data is passed from one component through multiple interdependent components until you get to the component where the data is needed. Here's an illustration of prop drilling to help you understand:  </p>
<p><img src="https://lh5.googleusercontent.com/K1veBT9r_aQPq_iYI9MdtljbsBu8egv7n8cu78fWqzL0POVn2xb66r_gEFgJ8qg9FxphsGFqNZIDQ3QZ0zuT-XtEcrpNVZylXvxhDTPAySL8_FJWiIGHlcXggcHYCFKaQeNp8HRQvCZZQHRULaf8_vtg8mgyZElVhkSiUYgicFQ0mo6zPgGve9-Pcg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Passing data through multiple components is not a good way of writing clean, reusable, and DRY code. </p>
<p>The React context API is a fast way of avoiding prop drilling and ensuring your data is managed globally without using a huge third-party state management app like <a target="_blank" href="https://redux.js.org/">Redux</a> and <a target="_blank" href="https://mobx.js.org/README.html">MobX</a>.</p>
<h2 id="heading-what-is-the-react-context-api">What is the React Context API?</h2>
<p>React context is a built-in API that uses the useContext hook to share data across components. </p>
<p>Imagine passing the data of an authenticated user from a parent component to a deep nested child component. This will be cumbersome if you need to pass the data through a lot of intermediate components. </p>
<p>A better approach to doing this is using React context to handle the data.  </p>
<h2 id="heading-how-to-use-the-react-context-api">How to Use the React Context API</h2>
<h3 id="heading-how-to-create-context">How to create context</h3>
<p>useContext is a built-in hook in React. You can start using the context API by importing the createContext function from React like this:</p>
<pre><code class="lang-app.js">Import {createContext} from ‘react’;
const AuthContext = createContext();
</code></pre>
<p>Here, we initialized our context and named it <strong>AuthContext.</strong> The next step is to provide the context.</p>
<h3 id="heading-how-to-provide-the-context-to-the-components-that-need-it">How to provide the context to the components that need it</h3>
<p>The context API uses a provider to pass data to its child components. You will have to wrap all components with a provider component.</p>
<pre><code class="lang-app.js">&lt;AuthContext.Provider value={...}&gt;
    &lt;ParentComponent/&gt;
&lt;AuthContext.Provider&gt;
</code></pre>
<p>The Provider component has a <strong>value</strong> prop as seen above. The value of the context can either be updated or set using the <strong>value</strong> prop. In our case, we will be setting the value prop to the name of our authenticated user.</p>
<pre><code class="lang-app.js">import React from ‘react’;

function App() {

    const username = “John Doe”

    return(
        &lt;AuthContext.Provider value={username}&gt;
            &lt;Dashboard/&gt;
        &lt;AuthContext.Provider&gt;
    )
}

export default App;
</code></pre>
<p>Hooray! All components inside this <strong>App</strong> component will have access to the username data. Next, let's see how to use the context.</p>
<h3 id="heading-how-to-consume-the-context">How to consume the context</h3>
<p>We can consume the context by using the <strong>useContext</strong> hook. Without passing data through nested components, you can access your context in any component you want. Here’s how.</p>
<pre><code class="lang-profile.js">import { useContext } from ‘react’;

const Profile = () =&gt; {

    const value = useContext(AuthContext);

    return (
        &lt;div&gt;
            {value}
        &lt;/div&gt;
    )
}

export default Profile
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Apart from solving the problem of prop drilling, you can also use React context for theme configuration, global state management and more. </p>
<p>Note that the React context API is not a replacement for a global state management tool like Redux and MobX. You can read more about React Context <a target="_blank" href="https://reactjs.org/docs/context.html">here</a>.</p>
<p>I hope you enjoyed this tutorial.</p>
<p><strong>Happy coding!</strong></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
