<?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" version="2.0"><channel><title><![CDATA[Hassan Bahati]]></title><description><![CDATA[Computer Scientist]]></description><link>https://blog.hassanbahati.com</link><generator>RSS for Node</generator><lastBuildDate>Fri, 17 Apr 2026 12:58:06 GMT</lastBuildDate><atom:link href="https://blog.hassanbahati.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[A Beginner’s Guide to Understanding Firebase]]></title><description><![CDATA[Firebase is a Backend-as-a-Service (BaaS) platform backed by Google that provides a comprehensive suite of tools and services for building, testing, deploying, and managing web and mobile applications. It eliminates the need for developers to set up ...]]></description><link>https://blog.hassanbahati.com/a-beginners-guide-to-understanding-firebase</link><guid isPermaLink="true">https://blog.hassanbahati.com/a-beginners-guide-to-understanding-firebase</guid><category><![CDATA[Firebase]]></category><category><![CDATA[firebaseAuth]]></category><category><![CDATA[Firebase hosting]]></category><category><![CDATA[firebase functions]]></category><category><![CDATA[firebase Storage]]></category><category><![CDATA[Cloud Firestore]]></category><dc:creator><![CDATA[Hassan Bahati]]></dc:creator><pubDate>Sun, 23 Mar 2025 13:35:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1741985103493/1779988b-6403-4755-90b0-d46ce9e61df8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Firebase is a Backend-as-a-Service (BaaS) platform backed by Google that provides a comprehensive suite of tools and services for building, testing, deploying, and managing web and mobile applications. It eliminates the need for developers to set up and manage backend infrastructure, allowing them to focus more on frontend development and great user experiences.</p>
<p>In this guide, we shall explore Firebase in detail, covering core functionalities, advantages and use cases.</p>
<h2 id="heading-what-is-firebase">What is Firebase?</h2>
<p>Firebase is a cloud-based platform that offers tools for AI, Analytics, Building, and Running your web and mobile applications. It provides a serverless architecture, meaning developers don’t have to worry about managing servers or backend logic manually.</p>
<p>Below is a breakdown of the tools provided by Firebase:</p>
<h3 id="heading-tools-for-building">Tools for Building</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1742726827803/37657588-1cb2-4618-ba66-0107aa571939.png" alt class="image--center mx-auto" /></p>
<ol>
<li><strong>Firebase Authentication</strong></li>
</ol>
<p>Firebase Authentication is a backend authentication service that helps developers add user authentication to their web and mobile apps. It provides easy-to-use SDKs, ready-made UI libraries and offers a wide variety of authentications methods including:</p>
<ul>
<li><p>Email &amp; Password Authentication — Users sign-in with email and password credentials.</p>
</li>
<li><p>Federated Identity Providers — Supports Google, Facebook, GitHub, Apple, SAML, Twitter and OpenID Connect.</p>
</li>
<li><p>Anonymous Authentication — Allows users to use an app without signing in, with an option of upgrade later.</p>
</li>
<li><p>Custom Authentication — Integrates with existing authentication systems.</p>
</li>
</ul>
<ol start="2">
<li><strong>App Check</strong></li>
</ol>
<p>App Check protects your application and backends from abuse by ensuring that incoming traffic is from legitimate instances of your application.</p>
<ol start="3">
<li><strong>Cloud Storage for Firebase</strong></li>
</ol>
<p>Cloud Storage for Firebase is a powerful, simple and cost-effective cloud-based object(file) storage solution that allows developers to store and serve user generated content such as images, videos and other files securely.</p>
<p>The Firebase Admin SDK can be used to manage storage buckets, create download URLs and use Google Cloud Storage APIs to access files.</p>
<ol start="4">
<li><strong>Firebase Realtime Database</strong></li>
</ol>
<p>Firebase Realtime Database is a NoSQL cloud-based database in which data is stored in JSON format. With Realtime database, data across all your client applications and the server is synchronized in real-time and all apps automatically receive updates with the newest data.</p>
<p>It is as well recommended to try <a target="_blank" href="https://firebase.google.com/docs/firestore">Cloud Firestore</a> for modern applications requiring richer data models, query-ability, scalability and higher availability.</p>
<p>Realtime Database has got capabilities that include: realtime data synchronization, offline data management, accessibility from various client devices, scalability across multiple databases, among others.</p>
<ol start="5">
<li><strong>Cloud Firestore</strong></li>
</ol>
<p>Cloud Firestore is a scalable and flexible NoSQL database built on <a target="_blank" href="https://cloud.google.com/">Google Cloud</a> infrastructure. Cloud Firestore provides real-time synchronization and offline support for mobile, web and server development. Similar to Firebase Realtime Database, it keeps your data synchronized across clients apps using realtime listeners.</p>
<p>Cloud Firestore has got capabilities that include: seamless integration with other Firebase and Google Products, supports flexible hierarchical data structures, enables performing of robust queries, it is designed to scale, among others.</p>
<ol start="6">
<li><strong>Firebase Hosting</strong></li>
</ol>
<p>Firebase Hosting is a production-grade web hosting service for developers to deploy web apps quickly and securely.</p>
<ol start="7">
<li><strong>App Hosting</strong></li>
</ol>
<p>Firebase App Hosting enables hosting for full-stack and dynamic applications seamlessly. It supports frameworks such as <a target="_blank" href="https://nextjs.org/">Next.js</a> and <a target="_blank" href="https://angular.io/">Angular</a> which can be automatically be deployed through GitHub actions.</p>
<ol start="8">
<li><strong>Firebase Data Connect</strong></li>
</ol>
<p>Firebase Data Connect is a relational database solution that helps you build and scale mobile and web apps using a fully managed PostgreSQL database powered by <a target="_blank" href="https://cloud.google.com/sql?hl=en">Cloud SQL</a>.</p>
<ol start="9">
<li><strong>Firebase Extensions</strong></li>
</ol>
<p>Firebase Extensions are pre-packaged solutions that automate common development tasks such as integrating third-party services and managing payments. With Firebase Extensions, you deploy functionality to your app quickly.</p>
<ol start="10">
<li><strong>Cloud Functions for Firebase</strong></li>
</ol>
<p>Cloud Functions for Firebase is a serverless computing solution that allows developers to run backend code in response to events triggered by background events and HTTPS requests.</p>
<ol start="11">
<li><strong>Emulator Suite</strong></li>
</ol>
<p>Firebase Emulator Suite is a set of advanced tools that provide local emulation of Firebase services, allowing developers to test their applications in a sandbox environment before deploying them to production.</p>
<h3 id="heading-tools-for-engaging">Tools for Engaging</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1742737239401/1c19db47-6a67-4a2d-88df-e7dd90100a43.png" alt class="image--center mx-auto" /></p>
<ol>
<li><strong>Google Analytics for Firebase</strong></li>
</ol>
<p>Google Analytics for Firebase allows you to collect detailed data on user behavior, demographics, events and more. This solution is ideal when one needs to understand how users interact with the app, tracking in-app events, and making data driven decisions.</p>
<ol start="2">
<li><strong>Firebase Remote Config</strong></li>
</ol>
<p>Sometimes, you will want to modify your client app or server’s behavior and appearance remote, without releasing an update, in such situations, Firebase Remote Config will be the answer. It enables you to change features, layouts, or text dynamically in your app without requiring an app update.</p>
<ol start="3">
<li><strong>Firebase A/B Testing</strong></li>
</ol>
<p>Firebase A/B Testing helps you test different variations of your app to understand what works best for user engagement and retention. Firebase A/B Testing comes in handy if you want to optimize features, UI elements, or app performance by testing different versions and gathering data on what performs best.</p>
<ol start="4">
<li><strong>Firebase Cloud Messaging (FCM)</strong></li>
</ol>
<p>Firebase Cloud Messaging (FCM) allows you to send notification messages to users thus driving user engagement and retention. It is perfect for sending push notifications, reminders or other in-app messages.</p>
<ol start="5">
<li><strong>Firebase In-App Messaging</strong></li>
</ol>
<p>Firebase In-App Messaging helps you to send targeted, contextually relevant messages within the app that encourage app exploration and discovery. It can be used when you want to deliver realtime, in-app messages to users to encourage actions like completing a profile, completing an order, etc.</p>
<h3 id="heading-tools-for-releasing-and-monitoring">Tools for Releasing and Monitoring</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1742737313407/0f10dc95-eaa6-4d9e-b5f6-352bccbe2985.png" alt class="image--center mx-auto" /></p>
<ol>
<li><strong>App Distribution</strong></li>
</ol>
<p>Firebase App Distribution is a tool for distributing you app to beta testers and collaborators before releasing it to the public.</p>
<ol start="2">
<li><strong>Firebase Crashlytics</strong></li>
</ol>
<p>Firebase Crashlytics enables you to achieve realtime crash and error reporting to track and fix app crashes, improve stability and enhance user experience. Firebase Crashlytics can be used to identify and troubleshoot app crashes, allowing you to prioritize fixing bugs and ensuring smoother user experiences.</p>
<ol start="3">
<li><strong>Firebase Performance Monitoring</strong></li>
</ol>
<p>Firebase Performance monitoring helps you to monitor your app’s performance by tracking metrics like app startup time, network requests, and slow views. It can be used to ensure optimal app performance, diagnose issues like slow load times, and improve user experience by resolving performance bottleneck</p>
<ol start="4">
<li><strong>Test Lab</strong></li>
</ol>
<p>Test Lab is cloud-based automated app testing environment that lets you test your application on a variety of real devices and configurations in order to gain insight on how it will perform with real users. Test Lab enables you to identify issues before release thus ensuring that your app functions as expected across different devices and OS versions.</p>
<h3 id="heading-tools-for-ai">Tools for AI</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1742736647867/a433f015-d319-478e-a640-28749314a790.png" alt class="image--center mx-auto" /></p>
<ol>
<li><strong>Firebase Genkit</strong></li>
</ol>
<p>Genkit is Firebase’s open-source TypeScript toolkit that helps developers integrate generative AI capabilities into their applications. Firebase Genkit offers a unified interface for integrating AI models from Google, OpenAI, Anthropic, Ollama, and more. Thereby, making it easy to build with a streamlined APIs for multimodal content generation, structured data generation, tool calling, human-in-the-loop, and other advanced capabilities.</p>
<p>Use Cases: AI chatbots, automated content generation, recommendation systems, workflow automations, intelligent agents, intelligent search systems and many others.</p>
<ol start="2">
<li><strong>Vertex AI in Firebase</strong></li>
</ol>
<p>Vertex AI in Firebase bridges the gap between your mobile or web application and direct integration with Vertex AI Gemini API or Imagen API. Vertex AI in Firebase SDKs offer security options against unauthorized, seamless integration with other Firebase services and thereby, enabling developers to build AI-powered mobile and web apps and features with the Gemini and Imagen models.</p>
<p>Use Cases: AI chatbots, Predictive analytics, recommendation engines, fraud detection, automated image classification and many others.</p>
<ol start="3">
<li><strong>Firebase Machine Learning</strong></li>
</ol>
<p>Firebase Machine Learning (Firebase ML) is a mobile SDK that enables developers to integrate machine learning capabilities into their apps (Android and Apple), whether using Google’s cloud-based models or custom TensorFlow Lite models for on-device inference.</p>
<p>Use Cases: Personalized AI Assistants, smart document processing, image-based search and recognition, voice and language translation, among others.</p>
<h2 id="heading-why-use-firebase">Why Use Firebase?</h2>
<p>Firebase is popular among developers due to its ease of use, scalability, and real-time data handling capabilities.</p>
<p>Here are some reasons why Firebase is a great choice;</p>
<ul>
<li><p>Fast Development: No need to build backend services from scratch. Firebase provides pre-configured solutions that can be quickly and easily set up.</p>
</li>
<li><p>Real-time Synchronization: Firebase databases sync data instantly across devices.</p>
</li>
<li><p>Cross-Platform Support: Works seamlessly for Web, Android, and IOS applications.</p>
</li>
<li><p>Scalability: Firebase is built on Google Cloud, making it suitable for small and large applications alike.</p>
</li>
<li><p>Security: Google-backed authentication and data security features.</p>
</li>
<li><p>Serverless Functions: Cloud Functions allow backend logic execution without server management.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Firebase is an excellent all-in-one web and mobile application development solution for building, monitoring, testing and engaging with your users. Whether you’re building a small project or a large-scale application, Firebase provides scalable, real-time, and secure backend services. Further more, Firebase integrates seamlessly with a couple of Google products such as <a target="_blank" href="https://firebase.google.com/firebase-and-gcp">Google Cloud</a>, <a target="_blank" href="https://firebase.google.com/docs/analytics">Google Analytics</a>, among others, making it a powerful solution for scalable and secure applications.</p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://firebase.google.com/">https://firebase.google.com/</a></p>
<p><a target="_blank" href="https://firebase.google.com/docs">https://firebase.google.com/docs</a></p>
]]></content:encoded></item><item><title><![CDATA[TanStack Query Firebase v1.0.7 for React: What’s New and How to Use It]]></title><description><![CDATA[TanStack Query Firebase is a powerful library that provides a set of hooks for handling asynchronous tasks with Firebase in your applications. This library simplifies real-time data fetching, caching, and syncing data in your applications.
On 7th Mar...]]></description><link>https://blog.hassanbahati.com/tanstack-query-firebase-v107-for-react-whats-new-and-how-to-use-it</link><guid isPermaLink="true">https://blog.hassanbahati.com/tanstack-query-firebase-v107-for-react-whats-new-and-how-to-use-it</guid><category><![CDATA[firestore]]></category><category><![CDATA[#Invertase]]></category><category><![CDATA[tanstack-query]]></category><category><![CDATA[Firebase]]></category><category><![CDATA[Cloud Firestore]]></category><dc:creator><![CDATA[Hassan Bahati]]></dc:creator><pubDate>Fri, 14 Mar 2025 17:02:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1741968763495/1ca761c9-aeba-4637-b8a7-296629b97d66.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>TanStack Query Firebase is a powerful library that provides a set of hooks for handling asynchronous tasks with Firebase in your applications. This library simplifies real-time data fetching, caching, and syncing data in your applications.</p>
<p>On 7th March, 2025, a new release, v1.0.7 was published. With the <strong>release of v1.0.7</strong>, the library introduces <strong>new react hooks</strong>. In this post, we'll explore <strong>what's new in v1.0.7</strong>, how to set up the library in a React project, and practical usage examples.</p>
<h2 id="heading-whats-new-in-v107httpswwwnpmjscompackagetanstack-query-firebasereactv107"><strong>What’s New in</strong> <a target="_blank" href="https://www.npmjs.com/package/@tanstack-query-firebase/react/v/1.0.7"><strong>v1.0.7</strong></a><strong>?</strong></h2>
<p>We've added more hooks for react, making it easier to manage data insertions, updates and deletion operations to <a target="_blank" href="https://firebase.google.com/docs/firestore">Cloud Firestore</a>. The new hooks include:</p>
<ul>
<li><p><code>useAddDocumentMutation</code> : Add a new document to specified <em>CollectionReference</em> with the given data, assigning it a document ID automatically.</p>
</li>
<li><p><code>useUpdateDocumentMutation</code> : Updates fields in the document referred to by the specified <em>DocumentReference</em>. The update will fail if applied to a document that does not exist.</p>
</li>
<li><p><code>useSetDocumentMutation</code> : Writes to the document referred to by this <em>DocumentReference</em>. If the document does not yet exist, it will be created.</p>
</li>
</ul>
<h2 id="heading-getting-started-with-tanstack-query-firebase-in-react"><strong>Getting Started with TanStack Query Firebase in React</strong></h2>
<h3 id="heading-1-install-dependencies"><strong>1. Install Dependencies</strong></h3>
<p>To use <strong>TanStack Query Firebase</strong>, install the required packages:</p>
<pre><code class="lang-bash">npm install @tanstack/react-query firebase @tanstack/query-firebase/react
</code></pre>
<h3 id="heading-2-setup-firebase-and-tanstack-query"><strong>2. Setup Firebase and TanStack Query</strong></h3>
<p>Configure Firebase in your project:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { getApps, 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-keyword">const</span> firebaseConfig = {
  apiKey: <span class="hljs-string">"YOUR_API_KEY"</span>,
  authDomain: <span class="hljs-string">"YOUR_AUTH_DOMAIN"</span>,
  projectId: <span class="hljs-string">"YOUR_PROJECT_ID"</span>,
  storageBucket: <span class="hljs-string">"YOUR_STORAGE_BUCKET"</span>,
  messagingSenderId: <span class="hljs-string">"YOUR_MESSAGING_SENDER_ID"</span>,
  appId: <span class="hljs-string">"YOUR_APP_ID"</span>,
};

<span class="hljs-keyword">const</span> firebaseApp = getApps().length === <span class="hljs-number">0</span> ? initializeApp(firebaseConfig) : getApps()[<span class="hljs-number">0</span>];
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> db = getFirestore(firebaseApp);
</code></pre>
<p>Now, wrap your app with <strong>QueryClientProvider</strong>:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { QueryClient, QueryClientProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">"@tanstack/react-query"</span>;

<span class="hljs-keyword">const</span> queryClient = <span class="hljs-keyword">new</span> QueryClient();

<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> (
    &lt;QueryClientProvider client={queryClient}&gt;
      &lt;MyComponent /&gt;
    &lt;/QueryClientProvider&gt;
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h2 id="heading-using-tanstack-query-firebase-v107-in-react"><strong>Using TanStack Query Firebase v1.0.7 in React</strong></h2>
<h3 id="heading-mutating-firestore-data"><strong>Mutating Firestore Data</strong></h3>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { useSetDocumentMutation } <span class="hljs-keyword">from</span> <span class="hljs-string">"@tanstack-query-firebase/react/firestore"</span>;
<span class="hljs-keyword">import</span> { collection, doc } <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">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">type</span> Expense = {
  amount: <span class="hljs-built_in">number</span>;
  category: <span class="hljs-built_in">string</span>;
  date: <span class="hljs-built_in">string</span>;
  description: <span class="hljs-built_in">string</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">CreateExpense</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> createExpenseMutation = useSetDocumentMutation(doc(collection(db, <span class="hljs-string">"expenses"</span>)));

  <span class="hljs-keyword">const</span> [expense, setExpense] = useState&lt;Expense&gt;({
    amount: <span class="hljs-number">0</span>,
    category: <span class="hljs-string">""</span>,
    date: <span class="hljs-string">""</span>,
    description: <span class="hljs-string">""</span>,
  });

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleChange</span>(<span class="hljs-params">e: React.ChangeEvent&lt;HTMLInputElement | HTMLSelectElement&gt;</span>) </span>{
    setExpense({ ...expense, [e.target.name]: e.target.value });
  }

  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleSubmit</span>(<span class="hljs-params">e: React.FormEvent</span>) </span>{
    e.preventDefault();

    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">await</span> createExpenseMutation.mutate(expense);
      setExpense({
        amount: <span class="hljs-number">0</span>,
        category: <span class="hljs-string">""</span>,
        date: <span class="hljs-string">""</span>,
        description: <span class="hljs-string">""</span>,
      });
    } <span class="hljs-keyword">catch</span> (error) {
       <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error adding expense:"</span>, error);
    }
  }
  <span class="hljs-keyword">return</span> (
    &lt;div&gt;
      &lt;form onSubmit={handleSubmit}&gt;
        &lt;div&gt;
          &lt;input
            name=<span class="hljs-string">"amount"</span>
            value={expense.amount}
            onChange={handleChange}
            <span class="hljs-keyword">type</span>=<span class="hljs-string">"number"</span>
            required
          /&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;select
            value={expense.category}
            onChange={handleChange}
            name=<span class="hljs-string">"category"</span>
            required
          &gt;
            &lt;option value={<span class="hljs-string">""</span>}&gt;Select Category&lt;/option&gt;
            &lt;option value={<span class="hljs-string">"food"</span>}&gt;Food&lt;/option&gt;
            &lt;option value={<span class="hljs-string">"transport"</span>}&gt;Transport&lt;/option&gt;
            &lt;option value={<span class="hljs-string">"internet"</span>}&gt;Internet&lt;/option&gt;
          &lt;/select&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;input
            name=<span class="hljs-string">"date"</span>
            value={expense.date}
            onChange={handleChange}
            <span class="hljs-keyword">type</span>=<span class="hljs-string">"date"</span>
            required
          /&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;input
            name=<span class="hljs-string">"description"</span>
            value={expense.description}
            onChange={handleChange}
            <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
            required
          /&gt;
        &lt;/div&gt;
        &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>&gt;
          {createExpenseMutation.isPending ? <span class="hljs-string">"Submitting"</span> : <span class="hljs-string">"Submit"</span>}
        &lt;/button&gt;
      &lt;/form&gt;
    &lt;/div&gt;
  );
};
</code></pre>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>TanStack Query Firebase <strong>v1.0.7</strong> brings react hooks to super charge your Firebase applications.</p>
<p>By leveraging <strong>TanStack Query Firebase</strong>, you get a <strong>declarative, efficient, and scalable</strong> way to manage real-time data fetching and mutations in your frontend apps.</p>
<p>🚀 <strong>Give it a try and upgrade your Firebase queries and mutations with TanStack Query Firebase!</strong></p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://invertase.docs.page/tanstack-query-firebase"><strong>https://invertase.docs.page/tanstack-query-firebase</strong></a></p>
<p><a target="_blank" href="https://firebase.google.com/"><strong>https://firebase.google.com/</strong></a></p>
]]></content:encoded></item><item><title><![CDATA[What Happens When You Import Anything in Node.js?]]></title><description><![CDATA[Ever wondered what really happens when you import a module in Node.js? How Node.js figures out where to find the file? Or why you sometimes get an error like:

To fully understand imports, we must first understand exports and how Node.js resolves mod...]]></description><link>https://blog.hassanbahati.com/what-happens-when-you-import-anything-in-nodejs</link><guid isPermaLink="true">https://blog.hassanbahati.com/what-happens-when-you-import-anything-in-nodejs</guid><category><![CDATA[Node.js]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[resolution]]></category><category><![CDATA[node_modules]]></category><dc:creator><![CDATA[Hassan Bahati]]></dc:creator><pubDate>Thu, 06 Mar 2025 22:18:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1741291400187/67109ccf-b7f7-4658-a7db-a87efee3f135.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Ever wondered what really happens when you import a module in Node.js? How Node.js figures out where to find the file? Or why you sometimes get an error like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1741291904292/77f3800b-6b58-4d13-9bb6-39e7d43f58fb.png" alt class="image--center mx-auto" /></p>
<p>To fully understand <strong>imports</strong>, we must first understand <strong>exports</strong> and how Node.js resolves modules. Let’s dive right in.</p>
<h2 id="heading-exports-how-modules-define-what-can-be-imported">Exports — How modules define what can be imported</h2>
<p>Originally, JavaScript code in Node.js was packaged using CommonJS modules.</p>
<blockquote>
<p>Node.js considers each file as a separate module.</p>
</blockquote>
<p>For instance, if you had a file called <code>index.js</code> with the following contents;</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> articles = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./article.js"</span>)

<span class="hljs-keyword">const</span> text = <span class="hljs-string">"This is an article i wrote about the Node.js module resolution algorithm."</span>
<span class="hljs-keyword">const</span> title = <span class="hljs-string">"What Happens When You Import Anything in Node.js?"</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The word count of the article is: ${article.wordCount(text)}"</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The length of the title is ${article.titleLength(title)}"</span>)
</code></pre>
<p>First off <code>index.js</code> loads the module <code>article.js</code> that is located in a directory relative to itself. The contents of <code>article.js</code> are as below;</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wordCount</span>(<span class="hljs-params">text</span>) </span>{
    <span class="hljs-keyword">return</span> text.split(<span class="hljs-regexp">/\s+/</span>).length;  <span class="hljs-comment">// Splitting text into words and counting them</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">titleLength</span>(<span class="hljs-params">title</span>) </span>{
    <span class="hljs-keyword">return</span> title.length;  <span class="hljs-comment">// Returning the length of the title string</span>
}

<span class="hljs-comment">// Exporting the functions</span>
<span class="hljs-built_in">exports</span>.wordCount = wordCount;
<span class="hljs-built_in">exports</span>.titleLength = titleLength;
</code></pre>
<p>The module <code>article.js</code> exports the functions <code>wordCount()</code> and <code>titleLength()</code>.</p>
<p>But, Node.js also supports ECMAScript standard which is supported by web browsers and other JavaScript runtimes. According to <a target="_blank" href="https://nodejs.org/api/esm.html#modules-ecmascript-modules">Node.js Documentation</a>, ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">import</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export">export</a> statements.</p>
<blockquote>
<p>A module needs to export something before it can be imported.</p>
</blockquote>
<p>Node.js as well allows modules to explicitely define <em>exports</em> in <code>package.json</code> as seen below;</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-package"</span>,
    <span class="hljs-attr">"exports"</span>: {
            <span class="hljs-attr">"./publications"</span>: <span class="hljs-string">"./article.js"</span>
        }
}
</code></pre>
<p>In the above <code>package.json</code> file, the exports defines what is exposed by the module. This can be handy when one needs to prevent unintended access to internal files.</p>
<p>The functions from module <code>article.js</code> can now be imported as below;</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { wordCount, titleLength } <span class="hljs-keyword">from</span> <span class="hljs-string">"my-package/publications"</span>

<span class="hljs-keyword">const</span> text = <span class="hljs-string">"This is an article i wrote about the Node.js module resolution algorithm."</span>
<span class="hljs-keyword">const</span> title = <span class="hljs-string">"What Happens When You Import Anything in Node.js?"</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The word count of the article is: ${wordCount(text)}"</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The length of the title is ${titleLength(title)}"</span>)
</code></pre>
<h2 id="heading-the-resolution-algorithm-how-nodejs-resolves-imports">The Resolution Algorithm — How Node.js Resolves Imports</h2>
<p>Node.js executes a strict procedure which is the resolution algorithm in order to check if <code>some-module</code> exists and if it does, where it is located in the file system. Several checks and tests are performed before a deduction is made.</p>
<p>Whenever you write;</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { anything } <span class="hljs-keyword">from</span> <span class="hljs-string">"some-module"</span>
</code></pre>
<p>The checks made are made for;</p>
<ul>
<li><p>Core modules</p>
</li>
<li><p>Relative modules</p>
</li>
<li><p>NPM packages</p>
</li>
<li><p>Directories</p>
</li>
<li><p>Alias Modules</p>
</li>
</ul>
<h3 id="heading-check-1-is-it-a-core-module">Check 1: Is It A Core Module?</h3>
<p>Node.js core modules are a set of modules which you can use off-the-self without manual installation.</p>
<p>Some core modules include; <code>fs</code>, <code>dns</code>, <code>events</code>, <code>os</code>, <code>path</code>, <code>url</code>, <code>util</code>, <code>stream</code>, and so many more….</p>
<p>Node.js will first check if the import matches one of the inbuilt modules.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">"fs"</span> <span class="hljs-comment">// Core Module</span>
</code></pre>
<p>If its a core module, it will immediately get loaded.</p>
<h3 id="heading-check-2-is-it-a-relative-module">Check 2: Is It A Relative Module?</h3>
<p>Secondly, Node.js will check if the module name starts with <code>/</code>, <code>./</code>, or <code>../</code>. If it does, then the proceeding content will be treated as a file path and search for the module location with commence.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { anything } <span class="hljs-keyword">from</span> <span class="hljs-string">"/some-module"</span>
<span class="hljs-keyword">import</span> { something } <span class="hljs-keyword">from</span> <span class="hljs-string">"./some-module"</span>
<span class="hljs-keyword">import</span> { things } <span class="hljs-keyword">from</span> <span class="hljs-string">"../some-module"</span>
</code></pre>
<p>If the module name starts with <code>/</code>, a search at the root of the file system will be made.</p>
<p>If the module name starts with <code>./</code> or <code>../</code> , a search will be made relative to the location of the current file.</p>
<h3 id="heading-check-3-is-it-an-npm-package">Check 3: Is It An NPM Package?</h3>
<p>This check search through <code>node_modules</code>.</p>
<p>If a module is not a core module and neither a relative module, Node.js will assume it a package installed from <a target="_blank" href="https://www.npmjs.com/">npm registry</a> and will commence a search through the <code>node_modules</code> directory.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useDocumentQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">"@tanstack-query-firebase/react"</span> <span class="hljs-comment">// Searches node_modules for @tanstack-query-firebase</span>
</code></pre>
<p>Node.js will check if <code>node_modules/@tanstack-query-firebase/react/package.json</code> exists.</p>
<p>If the <code>node_modules/@tanstack-query-firebase/react/package.json</code> exists, a check if there exists an <code>exports</code> field in the <code>package.json</code> . If exists, what is exposed by the <code>export</code> will be resolved.</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-package"</span>,
    <span class="hljs-attr">"exports"</span>: {
            <span class="hljs-attr">"./publications"</span>: <span class="hljs-string">"./article.js"</span>
        }
}
</code></pre>
<p>If the <code>node_modules/@tanstack-query-firebase/react/package.json</code> exists, and doesn’t have an <code>exports</code> field in the <code>package.json</code>. The <code>main</code> field will them be considered and its value will be resolved.</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-package"</span>,
    <span class="hljs-attr">"main"</span>: <span class="hljs-string">"./article.js"</span>
}
</code></pre>
<p>In the event that a <code>main</code> field doesn’t exist in the <code>package.json</code>, an available <code>index.js</code> or <code>index.mjs</code> file will be considered.</p>
<p>If <code>@tanstack-query-firebase</code> is not found at the current directory level, Node.js will move subsequent levels upwards the file system while checking for it.</p>
<pre><code class="lang-bash"> ./node_modules/@tanstack-query-firebase  
../node_modules/@tanstack-query-firebase  
../../node_modules/@tanstack-query-firebase
</code></pre>
<blockquote>
<p>Packages installed at the root of your file system are ideally be available to all Node.js apps on your system.</p>
</blockquote>
<h3 id="heading-check-4-is-it-a-directory">Check 4: Is It A Directory?</h3>
<p>If the import refers to a directory, Node.js will search for a <code>package.json</code> file in that directory. In the <code>package.json</code>, a <code>main</code> field as an entry will be looked out for.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> utils <span class="hljs-keyword">from</span> <span class="hljs-string">"./utils"</span>
</code></pre>
<p>If a <code>package.json</code> doesn’t exist, an <code>index.js</code> or <code>index.mjs</code> will be searched.</p>
<pre><code class="lang-bash">./utils/package.json (looks <span class="hljs-keyword">for</span> <span class="hljs-string">"main"</span> field)  
./utils/index.js  
./utils/index.mjs
</code></pre>
<h3 id="heading-check-5-additional-checks-and-considerations">Check 5: Additional Checks and Considerations</h3>
<p>Additionally, Node.js will check for an ESM vs CommonJS Compatibility.</p>
<p>If you import an ESM (<code>.mjs</code>) module into a CommonJS (<code>.cjs</code>) file, or vice versa, Node.js may throw an error.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// CommonJS (require)</span>
<span class="hljs-keyword">const</span> package = <span class="hljs-built_in">require</span>(<span class="hljs-string">'some-esm-module'</span>); <span class="hljs-comment">// Error if it's an ESM package</span>
</code></pre>
<p>To avoid conflicts, ensure your <code>package.json</code> has:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"type"</span>: <span class="hljs-string">"module"</span>
}
</code></pre>
<p>or explicitly use <code>.mjs</code> or <code>.cjs</code> extensions.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The Node.js Resolution Algorithm gives insight into what happens under the hood, every time we import anything in Node.js.</p>
<h2 id="heading-references">References</h2>
<h3 id="heading-httpsnodejsorgapipackageshtmlexportshttpsnodejsorgapipackageshtmlexports"><a target="_blank" href="https://nodejs.org/api/packages.html#exports">https://nodejs.org/api/packages.html#exports</a></h3>
<h3 id="heading-httpsnodejsorgapimoduleshtmlmodules-commonjs-moduleshttpsnodejsorgapimoduleshtmlmodules-commonjs-modules"><a target="_blank" href="https://nodejs.org/api/modules.html#modules-commonjs-modules">https://nodejs.org/api/modules.html#modules-commonjs-modules</a></h3>
<p><a target="_blank" href="https://nodejs.org/api/esm.html#modules-ecmascript-modules">https://nodejs.org/api/esm.html#modules-ecmascript-modules</a></p>
]]></content:encoded></item><item><title><![CDATA[Tanstack Query Firebase v1.0.6]]></title><description><![CDATA[On Thursday, 13th February, 2025, TanStack Query Firebase v1.0.6 officially went live! 🎉 This release brings new powerful hooks for Firebase Authentication and Firestore, making state management and data fetching in your React apps smoother and more...]]></description><link>https://blog.hassanbahati.com/tanstack-query-firebase-v106</link><guid isPermaLink="true">https://blog.hassanbahati.com/tanstack-query-firebase-v106</guid><category><![CDATA[Firebase]]></category><category><![CDATA[firebaseAuth]]></category><category><![CDATA[firestore]]></category><dc:creator><![CDATA[Hassan Bahati]]></dc:creator><pubDate>Sat, 15 Feb 2025 19:54:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739646351878/0accd6d3-37ab-48d5-b625-0b182ecfcdd0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>On Thursday, 13th February, 2025, <a target="_blank" href="https://invertase.docs.page/tanstack-query-firebase">TanStack Query Firebase</a> <a target="_blank" href="https://www.npmjs.com/package/@tanstack-query-firebase/react/v/1.0.6">v1.0.6</a> officially went live! 🎉 This release brings new powerful hooks for Firebase Authentication and Firestore, making state management and data fetching in your React apps smoother and more efficient. 🚀</p>
<h2 id="heading-whats-new-in-v106httpswwwnpmjscompackagetanstack-query-firebasereactv106">🔥 What’s New in <a target="_blank" href="https://www.npmjs.com/package/@tanstack-query-firebase/react/v/1.0.6">v1.0.6</a>?</h2>
<h3 id="heading-1-expanded-authentication-hooks">1. Expanded Authentication Hooks</h3>
<p>We've added more hooks to streamline authentication workflows, making it easier to manage user sessions, authentication states, and Firebase auth operations. The new hooks include:</p>
<ul>
<li><p><code>useApplyActionCodeMutation</code>: Applies a verification code sent to the user by email or other out-of-band mechanism.</p>
</li>
<li><p><code>useCheckActionCodeMutation</code> : Checks a verification code sent to the user by email or other out-of-band mechanism.</p>
</li>
<li><p><code>useCreateUserWithEmailAndPasswordMutation</code>: Creates a new user account associated with the specified email address and password.</p>
</li>
<li><p><code>useConfirmPasswordResetMutation</code>: Sends a password reset email to the given email address.</p>
</li>
<li><p><code>useRevokeAccessTokenMutation</code>: Revokes the given access token. Currently only supports Apple OAuth access tokens.</p>
</li>
<li><p><code>useGetRedirectResultQuery</code>: Gets a UserCredential from the redirect-based sign-in flow.</p>
</li>
</ul>
<p>These hooks integrate seamlessly provide a bunch of features out of the box, ensuring that authentication state remains fresh and efficient.</p>
<h3 id="heading-2-expanded-firestore-hooks">2. Expanded Firestore Hooks</h3>
<p>Firestore is at the heart of many Firebase applications, and <a target="_blank" href="https://www.npmjs.com/package/@tanstack-query-firebase/react/v/1.0.6">v1.0.6</a> enhances Firestore support with additional hooks:</p>
<ul>
<li><p><code>useEnableNetworkMutation</code>: Re-enables use of the network for a given Firestore instance after a prior disable network call.</p>
</li>
<li><p><code>useNamedQuery</code>: Reads a Firestore Query from local cache, identified by the given name.</p>
</li>
<li><p><code>useDeleteDocumentMutation</code>: Deletes the document referred to by the specified DocumentReference.</p>
</li>
</ul>
<p>These hooks simplify Firestore integration, allowing you to focus on building reactive and performant apps without worrying about state management.</p>
<h2 id="heading-installation">📦 Installation</h2>
<p>To upgrade or install <a target="_blank" href="https://www.npmjs.com/package/@tanstack-query-firebase/react">@tanstack-query-firebase/react v1.0.6</a>, run:</p>
<pre><code class="lang-sh">npm i @tanstack-query-firebase/react@latest
</code></pre>
<p>or with Yarn:</p>
<pre><code class="lang-sh">yarn add @tanstack-query-firebase/react@latest
</code></pre>
<p>or with pnpm:</p>
<pre><code class="lang-sh">pnpm i @tanstack-query-firebase/react@latest
</code></pre>
<h2 id="heading-get-started-today">🎯 Get Started Today!</h2>
<p>References:</p>
<p><a target="_blank" href="https://invertase.docs.page/tanstack-query-firebase">https://invertase.docs.page/tanstack-query-firebase</a></p>
<p><a target="_blank" href="https://firebase.google.com/">https://firebase.google.com/</a></p>
]]></content:encoded></item><item><title><![CDATA[Building a Real-Time Expense Tracker App with TanStack Query Firebase]]></title><description><![CDATA[TanStack Query Firebase is a library that provides a set of hooks for handling asynchronous tasks with Firebase in your applications. Managing state synchronization, caching and background data updates can be complex, but TanStack Query Firebase simp...]]></description><link>https://blog.hassanbahati.com/building-a-real-time-expense-tracker-app-with-tanstack-query-firebase</link><guid isPermaLink="true">https://blog.hassanbahati.com/building-a-real-time-expense-tracker-app-with-tanstack-query-firebase</guid><category><![CDATA[tanstack-query]]></category><category><![CDATA[Firebase]]></category><category><![CDATA[firestore]]></category><category><![CDATA[realtime]]></category><category><![CDATA[app]]></category><dc:creator><![CDATA[Hassan Bahati]]></dc:creator><pubDate>Fri, 31 Jan 2025 02:00:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738282553402/03e2b446-0851-41f7-b000-29090b9d31cc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://docs.page/invertase/tanstack-query-firebase"><strong>TanStack Query Firebase</strong></a> is a library that provides a set of hooks for handling asynchronous tasks with Firebase in your applications. Managing state synchronization, caching and background data updates can be complex, but TanStack Query Firebase simplifies these processes, making your firebase powered apps super efficient.</p>
<p>In this guide, we are going to build a real-time tracker app with TanStack Query Firebase. This app will allow users to:</p>
<ul>
<li><p>Add, edit and delete expenses.</p>
</li>
<li><p>Categorize expenses (Food, Rent, Travel, etc)</p>
</li>
<li><p>View reports and with total expenses.</p>
</li>
<li><p>Sync data in real-time with Firebase.</p>
</li>
</ul>
<p>By the end of this tutorial, we shall a fully functional real-time expense tracker 🔥</p>
<p>Let’s jump right in 🚀</p>
<h2 id="heading-step-1-setting-up-the-project">Step 1: Setting Up the project.</h2>
<p>First, we are going to create a react app and install the necessary dependencies.</p>
<pre><code class="lang-bash">pnpm create vite realtime-expense-tracker-app
</code></pre>
<p>On running the above command, select the framework as <code>React</code> and variant as <code>Typescript</code>. The following files will then get added into your current directory.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738284141845/0d111688-2109-414e-bbdf-cf7a31403a7e.png" alt class="image--center mx-auto" /></p>
<p>Next, we shall install <a target="_blank" href="https://docs.page/invertase/tanstack-query-firebase"><code>TanStack Query Firebase</code></a>, <a target="_blank" href="https://firebase.google.com/"><code>Firebase</code></a> and <a target="_blank" href="https://tanstack.com/query/latest"><code>TanStack Query</code></a>.</p>
<pre><code class="lang-bash">pnpm install @tanstack-query-firebase/react firebase @tanstack/react-query
</code></pre>
<h2 id="heading-step-2-configure-firebase">Step 2: Configure Firebase</h2>
<p>Go to the <a target="_blank" href="https://console.firebase.google.com/">firebase console</a>, create a project with the name <code>realtime-expense-tracker-app</code> and once created you will see screen below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738284800211/32d40cdf-ad9b-489b-aa9e-5d8b929422b0.png" alt class="image--center mx-auto" /></p>
<p>While in the <a target="_blank" href="https://console.firebase.google.com/">firebase console</a>, expand the <code>Build</code> option on the side menu and locate <code>Firestore Database</code>. When the <code>Firestore Database</code> option is clicked, you will see an action <code>Create database</code>, click it, follow the prompts, and your database will get created. You should now be able to see a screen as below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738285094617/ca2cc94d-1d32-4ca8-b055-04783c3df872.png" alt class="image--center mx-auto" /></p>
<p>Now, we need to register an app into our firebase project. To achieve this, we shall go the <code>Project Settings</code>. We shall then register our web app and the firebase config values will be availed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738285521233/ba25ba8c-0a43-491b-bb87-bd818142b68a.png" alt class="image--center mx-auto" /></p>
<p>Back in our project directory, we shall create a <code>.env</code> file to store our environment variables. Replace the placeholder values with the actual values of the firebase config above.</p>
<pre><code class="lang-bash">  VITE_FIREBASE_API_KEY=<span class="hljs-string">"your-firebase-apiKey"</span>
  VITE_FIREBASE_AUTH_DOMAIN=<span class="hljs-string">"your-firebase-authDomain"</span>
  VITE_FIREBASE_PROJECT_ID=<span class="hljs-string">"your-firebase-projectId"</span>
  VITE_FIREBASE_STORAGE_BUCKET=<span class="hljs-string">"your-firebase-storageBucket"</span>
  VITE_FIREBASE_MESSAGING_SENDER_ID=<span class="hljs-string">"your-firebase-messagingSenderId"</span>
  VITE_FIREBASE_APP_ID=<span class="hljs-string">"your-firebase-appId"</span>
</code></pre>
<h2 id="heading-step-3-initialize-firebase-and-tanstack-query">Step 3: Initialize Firebase and TanStack Query</h2>
<p>While in <code>src/main.tsx</code>, we are going to initialize <code>Firebase</code> and setup <code>TanStack Query</code> as seen below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738288683946/1c4e85bb-20e7-4c07-82b5-5ada17f6e08a.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-step-4-creating-expenses-list-component">Step 4: Creating Expenses List Component</h2>
<p>Now let’s create a file <code>src/components/expenses-list.tsx</code> in which we are going to setup a component to fetch and display the expenses using <code>TanStack Query Firebase</code>.</p>
<p>To achieve retrieval of data from our <a target="_blank" href="https://firebase.google.com/docs/firestore">Firestore Database</a>, we are going to use the <a target="_blank" href="https://docs.page/invertase/tanstack-query-firebase/react/firestore/hooks/useCollectionQuery"><code>useCollectionQuery</code></a> hook from <code>TanStack Query Firebase</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738286752449/ca323f28-3df9-4e61-bc12-03d60f585a8a.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://github.com/HassanBahati/tanstack-query-firebase-examples/tree/main/react/realtime-expense-tracker-app">https://github.com/HassanBahati/tanstack-query-firebase-examples/tree/main/react/realtime-expense-tracker-app</a></p>
]]></content:encoded></item><item><title><![CDATA[Getting Started With TanStack Query Firebase and Firebase Data Connect]]></title><description><![CDATA[TanStack Query Firebase provides a set of hooks for handling asynchronous tasks with Firebase in your applications. According to the official documentation: “Firebase Data Connect is Firebase's first relational database solution for developers who wa...]]></description><link>https://blog.hassanbahati.com/getting-started-with-tanstack-query-firebase-and-firebase-data-connect</link><guid isPermaLink="true">https://blog.hassanbahati.com/getting-started-with-tanstack-query-firebase-and-firebase-data-connect</guid><category><![CDATA[Firebase Data Connect]]></category><category><![CDATA[fdc]]></category><category><![CDATA[TanStack Query Firebase]]></category><category><![CDATA[Firebase]]></category><category><![CDATA[SQL]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[tanstack]]></category><category><![CDATA[tanstack-query]]></category><dc:creator><![CDATA[Hassan Bahati]]></dc:creator><pubDate>Fri, 03 Jan 2025 08:44:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734364724490/25af5465-0eee-4f4b-8703-148e45278516.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target="_blank" href="https://docs.page/invertase/tanstack-query-firebase">TanStack Query Firebase</a> provides a set of hooks for handling asynchronous tasks with Firebase in your applications. According to the <a target="_blank" href="https://firebase.google.com/docs/data-connect">official documentation</a>: “Firebase Data Connect is Firebase's first relational database solution for developers who want to create secure and scalable apps with Cloud SQL for PostgreSQL and type-safe mobile and web SDKs.</p>
<h2 id="heading-getting-started">Getting Started</h2>
<p>In this guide, we are going to create a <a target="_blank" href="https://react.dev/">react app</a> that leverages <code>useConnectQuery</code> and <code>useConnectMutation</code> from TanStack Query Firebase to perform CRUD operations to Firebase Data Connect.</p>
<p>Let’s jump right in!</p>
<h3 id="heading-step-1-bootstrapping-the-app">Step 1: Bootstrapping the app.</h3>
<p>Firstly, we are going to setup a react app using <a target="_blank" href="https://vite.dev/">vite</a>. To achieve this, we are going to run the command below.</p>
<pre><code class="lang-bash">pnpm create vite firebase-dataconnect-movies
</code></pre>
<p>On running the above command, we shall follow through the prompts and select <code>React</code> with <code>Typescript</code> options and a project will be scaffolded and will have the files as below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734385812661/df748700-23e9-402a-ba2e-3422ee2748db.png" alt class="image--center mx-auto" /></p>
<p>Open your terminal and while at the project root, run <code>pnpm install</code> to install dependencies.</p>
<p>Once the dependencies are successfully installed, run <code>pnpm dev</code> and a link will be availed through which you can view the project in your browser. This will look as below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734375719659/4d92e738-2759-43ee-b349-c8a3e18f8e56.png" alt class="image--center mx-auto" /></p>
<p>With that, we have successfully scaffolded our react application.</p>
<h3 id="heading-step-2-generating-data-connect-sdk-for-our-application">Step 2: Generating Data Connect SDK for our application.</h3>
<p>Firebase Data Connect uses <a target="_blank" href="https://graphql.org/learn/">GraphQL</a> for data modeling and definition of CRUD operations. With Firebase Data Connect and GraphQL, we are going to define schemas, queries and mutations, Data Connect will automatically generate custom SDKs for usage in the client logic.</p>
<p>Firstly, ensure that you have the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=GoogleCloudTools.firebase-dataconnect-vscode">Firebase Data Connect for VSCode Extension</a> installed. On clicking the Firebase Data Connect Extension icon, you will see a screen as below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734380094227/62c80e4a-9fce-4db6-8d13-8d2dea76bb22.png" alt class="image--center mx-auto" /></p>
<p>Here, we shall go ahead and click the <code>Run firebase init</code> button which will start a couple prompts in our terminal. The very first option will be to use an existing project or create new project, for which we shall select create new project and any name of your choice and in our case we are going to use <code>fdc-movies-app</code>. There after a firebase project will be created.</p>
<p>You will then be asked what connector should be setup for a generated SDK for, we shall select <code>firebase-dataconnect-movies/default</code> which is the suggested default option.</p>
<p>When all the above are successfully completed, you would have gone through the prompts as below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734381323802/491974f7-e5ab-4f9f-a76a-907790f28f87.png" alt class="image--center mx-auto" /></p>
<p>You can proceed to click enter and the current initialization terminal will close automatically.</p>
<p>At this point, in sidebar under the Firebase Data Connect Extension, you will have the following options</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734381549999/1bee3aa6-244c-4e90-aeb3-f2e829fd7206.png" alt class="image--center mx-auto" /></p>
<p>It is also important to note that a couple of files have also been generated into our project as below;</p>
<ul>
<li><p><code>.firebase</code> - folder</p>
</li>
<li><p><code>dataconnect</code> - folder</p>
</li>
<li><p><code>dataconnect-generated</code> - folder</p>
</li>
<li><p><code>.firebaserc</code> - file</p>
</li>
<li><p><code>firebase.json</code> - file</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734386075770/37697407-e691-42ba-b2e1-f447cfcb32fc.png" alt class="image--center mx-auto" /></p>
<p>We now need to go into the <code>dataconnect</code> folder and uncomment all the contents of the <code>mutations.gql</code>, <code>queries.gql</code> and <code>schema.gql</code> files. All code in those files is initially commented out. After uncommenting, these will look as below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734382137197/3488ef3a-f51a-4669-bf94-03400513efc4.png" alt class="image--center mx-auto" /></p>
<p>At this point, the generation of the Data Connect SDK is complete and it is currently connected to your application.</p>
<p>Since we are going to be testing locally, we shall need to start the emulators by clicking the <code>Start emulators</code> button under Firebase Data Connect Extension. On clicking this button, the emulators will and the extension will show as below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734397980383/53e032dc-7828-4d6a-8cb5-3bea3d6d274f.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-step-3-initialization-of-firebase-and-tanstack-query">Step 3: Initialization of Firebase and TanStack Query.</h3>
<p>In <code>Step 2</code>, we did create a firebase project called <code>fdc-movies-app</code>. When we head over to the <a target="_blank" href="https://console.firebase.google.com/">firebase console</a>, we should be able to find our project listed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734383811992/2e5abd31-e2b3-40a2-a307-6b144b000b66.png" alt class="image--center mx-auto" /></p>
<p>While in our project, we shall need to register an app. We are going to register a web app and we shall do that by selecting the <code>Web</code> option. We shall proceed to register our app with a name of our choice which could be <code>fdc-movies-app</code> and then the Firebase SDK config object will be availed as below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734384106862/1f2ada9a-a92a-4837-9ff0-33f6c90a3333.png" alt class="image--center mx-auto" /></p>
<p>We shall then head over to our project and add a <code>.env</code> file to store our environment variables and replace the placeholder values with the actual values from the above <code>firebaseConfig</code> object. Please note all these will be prefixed with <code>VITE_</code> since we are using Vite.</p>
<pre><code class="lang-bash">  VITE_FIREBASE_API_KEY=<span class="hljs-string">"your-firebase-apiKey"</span>
  VITE_FIREBASE_AUTH_DOMAIN=<span class="hljs-string">"your-firebase-authDomain"</span>
  VITE_FIREBASE_PROJECT_ID=<span class="hljs-string">"your-firebase-projectId"</span>
  VITE_FIREBASE_STORAGE_BUCKET=<span class="hljs-string">"your-firebase-storageBucket"</span>
  VITE_FIREBASE_MESSAGING_SENDER_ID=<span class="hljs-string">"your-firebase-messagingSenderId"</span>
  VITE_FIREBASE_APP_ID=<span class="hljs-string">"your-firebase-appId"</span>
</code></pre>
<p>Next, we are going to install the <code>firebase</code> and <code>@tanstack/react-query</code> packages using the commands below;</p>
<pre><code class="lang-bash">pnpm i firebase @tanstack/react-query
</code></pre>
<p>We are then going to modify our <code>src/main.tsx</code> so as to initialize a firebase app and initialize a Data Connect emulator connection as seen below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734394423705/5d72a7a2-a8f7-480c-9102-d92468525faf.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-step-4-crud-operations-with-useconnectmutation-and-useconnectquery">Step 4: CRUD operations with <code>useConnectMutation</code> and <code>useConnectQuery</code></h3>
<p><code>useConnectMutation</code> and <code>useConnectQuery</code> are hooks availed by TanStack Query Firebase. <code>useConnectMutation</code> enables you to perform <code>create</code>, <code>update</code> and <code>delete</code> operations while <code>useConnectQuery</code> enables you to <code>read</code>/<code>retrieve</code> data records stored in your database.</p>
<p>To get started with TanStack Query Firebase, we shall install the library using the following command.</p>
<pre><code class="lang-bash">pnpm i @tanstack-query-firebase/react
</code></pre>
<p>We are going to use the <code>useConnectQuery</code> hook to fetch the movies data as seen below. This will be done in the <code>src/App.tsx</code> file.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">"./App.css"</span>;
<span class="hljs-keyword">import</span> {useConnectQuery} <span class="hljs-keyword">from</span> <span class="hljs-string">"@tanstack-query-firebase/react"</span>;
<span class="hljs-keyword">import</span> {listMoviesRef} <span class="hljs-keyword">from</span> <span class="hljs-string">"@firebasegen/default-connector"</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">const</span> { data, isLoading, isSuccess, isError } = useConnectQuery(listMoviesRef());

<span class="hljs-keyword">return</span>(
       &lt;div&gt;
          {isLoading &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}
          {isError &amp;&amp; &lt;p&gt;Sorry, an error occurred.&lt;/p&gt;}
          {isSuccess &amp;&amp; data.movies.length &gt; <span class="hljs-number">0</span> ? (
            &lt;div className=<span class="hljs-string">"movies-grid"</span>&gt;
              {data.movies.map(<span class="hljs-function">(<span class="hljs-params">movie, index</span>) =&gt;</span> (
                &lt;div className=<span class="hljs-string">"movie-card"</span> key={index}&gt;
                  &lt;img src={movie.imageUrl} alt={movie.title} /&gt;
                  &lt;h3&gt;{movie.title}&lt;/h3&gt;
                  &lt;p&gt;Genre: {movie.genre}&lt;/p&gt;
                &lt;/div&gt;
              ))}
            &lt;/div&gt;
          ) : (
            &lt;p&gt;No movies found!&lt;/p&gt;
          )}
        &lt;/div&gt;
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>For creating movies, we are going to use the <code>useConnectMutation</code> hook, and we are going to set it up as below;</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-string">"./App.css"</span>;
<span class="hljs-keyword">import</span> {useConnectMutation} <span class="hljs-keyword">from</span> <span class="hljs-string">"@tanstack-query-firebase/react"</span>;
<span class="hljs-keyword">import</span> {createMovieRef} <span class="hljs-keyword">from</span> <span class="hljs-string">"@firebasegen/default-connector"</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">const</span> [movie, setMovie] = useState({
    title: <span class="hljs-string">""</span>,
    imageUrl: <span class="hljs-string">""</span>,
    genre: <span class="hljs-string">""</span>,
  });

  <span class="hljs-keyword">const</span> [error, setError] = useState(<span class="hljs-string">""</span>);

   <span class="hljs-keyword">const</span> createMovieMutation = useConnectMutation(createMovieRef, {
        invalidate: [listMoviesRef()],
        onSuccess: <span class="hljs-function">() =&gt;</span> {
          setMovie({ title: <span class="hljs-string">""</span>, imageUrl: <span class="hljs-string">""</span>, genre: <span class="hljs-string">""</span> });
        },
        onError: <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
          setError(<span class="hljs-string">"Failed to add movie. Please try again."</span>);
          <span class="hljs-built_in">console</span>.error(error);
        },
     });

  <span class="hljs-keyword">const</span> handleInputChange = <span class="hljs-function">(<span class="hljs-params">e: React.ChangeEvent&lt;HTMLInputElement&gt;</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> { name, value } = e.target;
    setMovie(<span class="hljs-function">(<span class="hljs-params">prevMovie</span>) =&gt;</span> ({
      ...prevMovie,
      [name]: value,
    }));
  };

  <span class="hljs-keyword">const</span> handleFormSubmit = <span class="hljs-function">(<span class="hljs-params">e: React.FormEvent</span>) =&gt;</span> {
    e.preventDefault();

    <span class="hljs-keyword">if</span> (!movie.title || !movie.imageUrl || !movie.genre) {
      setError(<span class="hljs-string">"All fields are required."</span>);
      <span class="hljs-keyword">return</span>;
    }

    setError(<span class="hljs-string">""</span>);
    createMovieMutation.mutate(movie);
  };

<span class="hljs-keyword">return</span>(
      &lt;div className=<span class="hljs-string">"movie-form"</span>&gt;
          &lt;h2&gt;Add a New Movie&lt;/h2&gt;
          &lt;form onSubmit={handleFormSubmit}&gt;
            &lt;div&gt;
              &lt;label&gt;Title:&lt;/label&gt;
              &lt;input
                <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
                name=<span class="hljs-string">"title"</span>
                value={movie.title}
                onChange={handleInputChange}
                placeholder=<span class="hljs-string">"Movie Title"</span>
              /&gt;
            &lt;/div&gt;
            &lt;div&gt;
              &lt;label&gt;Image URL:&lt;/label&gt;
              &lt;input
                <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
                name=<span class="hljs-string">"imageUrl"</span>
                value={movie.imageUrl}
                onChange={handleInputChange}
                placeholder=<span class="hljs-string">"Movie Image URL"</span>
              /&gt;
            &lt;/div&gt;
            &lt;div&gt;
              &lt;label&gt;Genre:&lt;/label&gt;
              &lt;input
                <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
                name=<span class="hljs-string">"genre"</span>
                value={movie.genre}
                onChange={handleInputChange}
                placeholder=<span class="hljs-string">"Movie Genre"</span>
              /&gt;
            &lt;/div&gt;
            &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span> disabled={createMovieMutation.isPending}&gt;
              {createMovieMutation.isPending ? <span class="hljs-string">"Adding..."</span> : <span class="hljs-string">"Add Movie"</span>}
            &lt;/button&gt;
          &lt;/form&gt;
          {error &amp;&amp; &lt;p className=<span class="hljs-string">"error-message"</span>&gt;{error}&lt;/p&gt;}
        &lt;/div&gt;
    )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>For the full code, please checkout the <a target="_blank" href="https://github.com/HassanBahati/tanstack-query-firebase-examples/blob/main/react/firebase-dataconnect-movies/src/App.tsx">src/App.tsx</a> on GitHub.</p>
<p>When we visit our browser, the interface will be as in the image below. Here, new movies can be added and will appear in the list right away.</p>
<p>Please note that the Data Connect emulator has to be running as seen in <code>Step 2</code>, otherwise the connection to the database will fail.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734395458874/609b6134-a9fc-4c21-8cad-c93d184e33c6.png" alt class="image--center mx-auto" /></p>
<p>Congratulations!</p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://github.com/HassanBahati/tanstack-query-firebase-examples/tree/main/react/firebase-dataconnect-movies">https://github.com/HassanBahati/tanstack-query-firebase-examples/tree/main/react/firebase-dataconnect-movies</a></p>
<p><a target="_blank" href="https://firebase.google.com/docs/data-connect/">https://firebase.google.com/docs/data-connect/</a></p>
<p><a target="_blank" href="https://graphql.org/learn/">https://graphql.org/learn/</a></p>
]]></content:encoded></item><item><title><![CDATA[hello, world!]]></title><description><![CDATA[hello, world!
I am Hassan Bahati. I am software engineer with a computer science background.
I am working on AI-Powered applications.
Ask me anything about Firebase!]]></description><link>https://blog.hassanbahati.com/hello-world</link><guid isPermaLink="true">https://blog.hassanbahati.com/hello-world</guid><category><![CDATA[HassanBahati]]></category><category><![CDATA[Firebase]]></category><dc:creator><![CDATA[Hassan Bahati]]></dc:creator><pubDate>Tue, 07 May 2024 17:00:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715336364208/99d2aafa-049a-4449-bb2a-2eda89d9307f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>hello, world!</p>
<p>I am Hassan Bahati. I am software engineer with a computer science background.</p>
<p>I am working on AI-Powered applications.</p>
<p>Ask me anything about Firebase!</p>
]]></content:encoded></item><item><title><![CDATA[What are Microservices?]]></title><description><![CDATA[In recent times one word you won't miss hearing around technology and developer spaces is microservices. For a long time, I kept pondering and deeply curious about what these microservices really were.
With seasoned experience in building application...]]></description><link>https://blog.hassanbahati.com/what-are-microservices-550f235009cb</link><guid isPermaLink="true">https://blog.hassanbahati.com/what-are-microservices-550f235009cb</guid><dc:creator><![CDATA[Hassan Bahati]]></dc:creator><pubDate>Mon, 05 Sep 2022 19:13:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715337075711/5c3e4e7f-bd30-4f40-81f2-3fe39b1dceda.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In recent times one word you won't miss hearing around technology and developer spaces is microservices. For a long time, I kept pondering and deeply curious about what these microservices really were.</p>
<p>With seasoned experience in building applications as one package which one may call monolithic architecture, I grew a burning curiosity to adventure if there existed any other approaches.</p>
<p>Monolithic Servers are a scenario where we have one single codebase which is deployed as one discrete unit. This server contains all the routing, middleware, business logic, and database access needed to <strong>implement all features of the entire application.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715337074108/5c55c61f-2fdc-4134-8718-a186ef812a21.jpeg" alt /></p>
<p>Monolithic Architecture</p>
<p>The above image depicts a typical monolithic architecture where the middleware and router serve all features that interact with a common database.</p>
<p>On the other hand, microservice architecture is quite different from that approach to build servers.</p>
<p>A single microservice contains all the routing, middleware, business logic, and database access needed to <strong>implement one single feature of the application.</strong></p>
<p>Microservice Architecture</p>
<p>In the above image, features are broken down into service that run independent of one another. Each service contains all middleware, router and database to enable it to function.</p>
<p>Microservices architecture eliminates single points of failure in an application by preventing tight coupling and dependency between features of an application.</p>
<p>For instance, in a blog app, posts and comments could be considered separate but independent services. The goal would be to prevent the dependency of the comments on posts as would they often appear with monolithic apps. Given that the posts service is broken, the comments service should be able to add comments to existing posts. In a deep dive, we would perhaps require a query service as an intermediary which would keep track of created posts and their respective comments.</p>
<p>Microservices have many pros and of course, as it is with any technology, there are downsides. The biggest challenge with microservices is <strong>data management between the different services</strong>. The question we always have to ask is how are we going to access existing data in the app since there is no interaction across service databases.</p>
<p><strong>References;</strong></p>
<p><a target="_blank" href="https://www.googleadservices.com/pagead/aclk?sa=L&amp;ai=DChcSEwjy-onnrv75AhV8j2gJHZDDB8wYABAAGgJ3Zg&amp;ohost=www.google.com&amp;cid=CAESbOD2W3AUOfzSxhqU5Ux3n4NDcm3ABkse9QmX6sKsDx0x9LVlBDXxl6myDZfgPHk2kJf1mC5LdMr1FuF-wym83zbWyF_QNTjKzaH4h8lBoZ4AwyLTKdvNBUu8-nXTPwTJHt0Z4uR5YI1ddxbcDA&amp;sig=AOD64_14hFjvabI3eMg_rpaiD9cs45VpVw&amp;q&amp;adurl&amp;ved=2ahUKEwitvoLnrv75AhUN3KQKHSP-CjAQ0Qx6BAgCEAE">Microservices with Node JS and React | Udemy</a></p>
<p><a target="_blank" href="https://microservices.io/patterns/index.html">microservices.io</a></p>
]]></content:encoded></item><item><title><![CDATA[CSS Flexbox Vs Float Vs Grid]]></title><description><![CDATA[In this article, we shall in depth understand the different CSS layout techniques.
CSS Flex-Box
The Flexible Box Layout Module, makes it easier to design flexible responsive layout structure without using float or positioning.
CSS for whole container...]]></description><link>https://blog.hassanbahati.com/css-flexbox-vs-float-vs-grid-f4a1e0204e20</link><guid isPermaLink="true">https://blog.hassanbahati.com/css-flexbox-vs-float-vs-grid-f4a1e0204e20</guid><category><![CDATA[CSS]]></category><category><![CDATA[flexbox]]></category><category><![CDATA[grid]]></category><dc:creator><![CDATA[Hassan Bahati]]></dc:creator><pubDate>Tue, 02 Feb 2021 10:48:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715337097373/a50e840e-3731-4877-8f55-1e13b295c302.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we shall in depth understand the different CSS layout techniques.</p>
<h4 id="heading-css-flex-box"><strong>CSS Flex-Box</strong></h4>
<p>The Flexible Box Layout Module, makes it easier to design flexible responsive layout structure without using float or positioning.</p>
<p><strong>CSS for whole container</strong></p>
<pre><code class="lang-plaintext">display: flexbox | inline-flex;  
flex-direction: row | row-reverse | column | column-reverse;  
flex-wrap: nowrap | wrap | wrap-reverse;  
flex-flow: &lt;‘flex-direction’&gt; || &lt;‘flex-wrap’&gt;  
justify-content: flex-start | flex-end | center | space-between | space-around;  
align-items: flex-start | flex-end | center | baseline | stretch;  
align-content: flex-start | flex-end | center | space-between | space-around | stretch;
</code></pre>
<p><strong>CSS for items in a container</strong></p>
<pre><code class="lang-plaintext">order: &lt;integer&gt;;  
flex-grow: &lt;number&gt;; /* default 0 */  
flex-shrink: &lt;number&gt;; /* default 1 */  
flex-basis: &lt;length&gt; | auto; /* default auto */  
flex: none | [ &lt;'flex-grow'&gt; &lt;'flex-shrink'&gt;? || &lt;'flex-basis'&gt; ]  
align-self: auto | flex-start | flex-end | center | baseline | stretch;
</code></pre>
<p><strong>Property #1:</strong><code>**display: flex**</code></p>
<p>A container’s default <code>display: block</code> in this context, <code>display: flex</code> tells your browser ‘’I want to make this container flexible.’’</p>
<p><img src="https://cdn-images-1.medium.com/max/800/0*mK57U3bfNzRmAkZX" alt /></p>
<p>Source: Scott Domes</p>
<p>Initially, each of the four containers (green, orange, red, blue) are defaulted with <code>display: block</code> thereby take all space from right to left.</p>
<p><strong>Property#2:</strong><code>**Flex direction**</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715337085173/53f62333-ce34-4121-89ee-22752ccfe9d9.png" alt /></p>
<p>Flexbox terminology diagram from <a target="_blank" href="https://www.w3.org/TR/css-flexbox-1/">official W3C specification</a>.</p>
<p>On application of flex property, we create a flexbox with two axes as showed above. This is why your squares defaulted to a horizontal line once you applied <code>display: flex</code>.</p>
<pre><code class="lang-plaintext">#container {  display: flex;  flex-direction: column;}
</code></pre>
<p><img src="https://cdn-images-1.medium.com/max/800/0*4MfktKKhutbAHR7W" alt /></p>
<p>Source: Scott Domes</p>
<p><code>flex-direction: column</code> is an interesting property in that it doesn’t align content on the cross axis instead of main axis. <strong>It alters the main axis from horizontal to vertical.</strong></p>
<p><strong>Property#3:</strong><code>Justify content</code></p>
<p>Justify content determines how items are aligned along the main axis. Attributes include; <strong>Flex-start: Flex-end, Center, Space-between (gives equal space between each square, but not between it and the container), Space-around(puts an equal space on either side of the square).</strong></p>
<pre><code class="lang-plaintext">#container {  display: flex;  flex-direction: row;  justify-content: flex-start;}
</code></pre>
<p><img src="https://cdn-images-1.medium.com/max/800/0*WI5BYaNdvzroKdKS" alt /></p>
<p>Source: Scott Domes</p>
<p><strong>Property#4:</strong><code>Align items</code></p>
<p>With a recap from justify-content that works applies to the main axis, align-items applies to the cross axis. flex-start, flex-end, center, stretch(items take up the entirety of the cross-axis), baseline(bottom of the paragraph tags are aligned).</p>
<p><img src="https://cdn-images-1.medium.com/max/800/0*R4zs30XsowkV6KA3" alt /></p>
<p>Source: Scott Domes</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715337090731/67a183a3-f50e-4a61-a184-84741a3b0040.png" alt /></p>
<p>Source: Scott Domes</p>
<p>Property#5: <code>Align self</code><br />Align-self property helps us to align individual items thereby overriding the align-items though it follows the rule for the entire container.<br /><code>#container { align-items: flex-start;}</code><br /><code>.square#one { align-self: center;}// Only this square will be centered.</code></p>
<p><img src="https://cdn-images-1.medium.com/max/800/0*teaf-1aEwVv5OR97" alt /></p>
<p>Source: Scott Domes</p>
<p><strong>CSS Float</strong></p>
<p>When we add <code>float: left;</code> to a container, the elements will be positioned to the left of the other .</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715337094279/671e4f87-41f9-489b-9401-0a5acbd62aea.png" alt /></p>
<p>before</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715337095784/99c01e43-2947-4fd5-82ed-dbcb7cc23b2a.png" alt /></p>
<p>after</p>
<p>Further more, when we add <code>float: right;</code> to the float items, they will be to the right of the containers and side by side to each other from right to the left.</p>
<p>The most applicable use of floats is when designing a navigation bar.</p>
<p><strong>CSS Grid</strong><br /><code>display: grid;</code> is newest and most powerful layout system in CSS. It offers 2-dimensional layouts thereby you handles both rows and columns unlike flexbox which is largely 1-dimensional. You work with Grid layout by applying CSS rules to both the parent element (which becomes the Grid Container) and to its children (which become the Grid Items).<br /><strong>Grid Container</strong></p>
<pre><code class="lang-plaintext">`grid-container {  display: grid | inline-grid }  
grid-template-rows { &lt;integer&gt; &lt;integer&gt; } /**specifies number of columns **/  
gird-template-columns { &lt;integer&gt; &lt;integer&gt; &lt;integer&gt; &lt;integer&gt; }` /\*\* specifies number of columns \*\*/  
justify-content { space-evenly | space-between | center | end }  
align-content { center | space-evenly | space-around | space-between | start | end }
</code></pre>
<p>When you assign the <code>display</code> property of a container to <code>grid</code> , every element in it becomes a grid item.</p>
<p><strong>Conclusion</strong></p>
<p>Besides the above explained CSS layout techniques, you can use CSS libraries such as Bootstrap, Material UI, Semantic UI, etc. to make web pages responsive.</p>
<p>references: <a target="_blank" href="https://www.w3schools.com/css">w3schools</a> , <a target="_blank" href="https://css-tricks.com">css-tricks.com</a></p>
]]></content:encoded></item></channel></rss>