<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zainab Ghauri on Medium]]></title>
        <description><![CDATA[Stories by Zainab Ghauri on Medium]]></description>
        <link>https://medium.com/@zainabghauri7799?source=rss-5a73d85d21de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jAQ-uQiXCaMuEeCwkZNOGA.jpeg</url>
            <title>Stories by Zainab Ghauri on Medium</title>
            <link>https://medium.com/@zainabghauri7799?source=rss-5a73d85d21de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:40:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zainabghauri7799/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[User Impersonation Using Keycloak: Why It Matters and How to Implement It]]></title>
            <link>https://medium.com/@zainabghauri7799/user-impersonation-using-keycloak-why-it-matters-and-how-to-implement-it-fd305d0b7150?source=rss-5a73d85d21de------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd305d0b7150</guid>
            <dc:creator><![CDATA[Zainab Ghauri]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 12:29:30 GMT</pubDate>
            <atom:updated>2025-12-16T14:35:22.796Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications need more than basic authentication. As systems scale, identity management must support secure access, troubleshooting, and support workflows without compromising security.</p><blockquote><strong>Why User Impersonation Is Important</strong></blockquote><p>User impersonation allows an <strong>authorized user</strong> (typically an administrator or support Admins )to temporarily act as another user <em>without knowing their credentials</em>.</p><p>When implemented correctly, impersonation provides several key benefits:</p><ul><li><strong>Faster issue debugging</strong> by experiencing the application exactly as the user does</li><li><strong>Improved customer support</strong> without password sharing or insecure workarounds</li><li><strong>Stronger security</strong> compared to manual logins or shared accounts</li><li><strong>Clear auditability and accountability</strong> when impersonation sessions are logged</li></ul><p>With proper role-based access control (RBAC), impersonation becomes a secure and efficient tool rather than a security risk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*BW4KLQapahykPaHsvyoQVQ.png" /></figure><h3>Keycloak Essentials: Performing User Impersonation Safely</h3><p>Just in case you’re not familiar with Keycloak , It is an open-source Identity and Access Management (IAM) solution that provides:</p><ul><li>Single Sign-On (SSO)</li><li>User and session management</li><li>Role-based access control</li><li>Multi-factor authentication</li><li>Support for OpenID Connect and OAuth 2.0</li></ul><p>For impersonation, Keycloak ensures:</p><ul><li>User credentials are never exposed</li><li>Only authorized roles can impersonate</li><li>Full audit logs are maintained</li><li>Proper access tokens are issued for the impersonated user</li></ul><p>By handling impersonation at the identity layer, applications remain simpler, safer, and fully auditable.</p><blockquote><strong><em>Why Choose Keycloak Impersonation Instead of Rolling Your Own?</em></strong></blockquote><p>Keycloak’s impersonation feature is powerful precisely because of its <strong>simplicity</strong>. What would normally require complex session handling, token manipulation, and security checks is reduced to <strong>a single, well-defined operation</strong> , and it works seamlessly out of the box.</p><p>When performed through the <strong>Keycloak Admin UI</strong>, impersonation is literally one click. Keycloak handles everything behind the scenes: session creation, token issuance, and auditing. The same behavior is available programmatically through the Admin REST API.</p><h3>Programmatic Impersonation with a Single API Call</h3><p>Keycloak exposes a dedicated endpoint for impersonation , <strong>Before calling this endpoint, make sure your admin user has the </strong><strong>impersonation role</strong>. Without it, Keycloak will return a <strong>403 Forbidden</strong> error.</p><pre>POST /admin/realms/{realm}/users/{user-id}/impersonation</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUBsiSm6mqlPibJ8mXQWCw.png" /><figcaption>Keycloak Impersonation Role</figcaption></figure><p>When this endpoint is called by an authorized admin, Keycloak responds with:</p><pre>{<br>  &quot;redirect&quot;: &quot;http://{keycloakServerUrl}/realms/${realmID}/account&quot;,<br>  &quot;sameRealm&quot;: false<br>}</pre><blockquote><strong><em>What Happens After the Redirect?</em></strong></blockquote><p>Redirecting the browser to the provided URL completes the impersonation flow.</p><p>At this point:</p><ul><li>Keycloak sets the <strong>Keycloak Identity cookie</strong></li><li>The <strong>original admin’s session ends</strong> and a <strong>new session is created</strong> for the impersonated user</li><li>The admin is now authenticated <strong>on behalf of that user</strong></li><li>All subsequent requests behave exactly as if the user logged in normally</li></ul><p>From the application’s perspective, nothing special is required, authentication and authorization work as usual.</p><blockquote><strong><em>Built-in Impersonation Tracking and Auditability</em></strong></blockquote><p>One of the biggest advantages of using Keycloak’s impersonation is <strong>native traceability</strong>.</p><p>Keycloak internally tracks:</p><ul><li>The <strong>impersonator’s user ID</strong></li><li>The <strong>impersonator’s username or email</strong></li></ul><p>To expose this information to your application, Keycloak provides <strong>predefined protocol mappers</strong> that can be added to your client:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*GxBenucRgF_1kCgbaqdwtQ.png" /><figcaption>Pre-defined Keycloak Mappers</figcaption></figure><p>Once configured, the issued access token will automatically include these claims during impersonation.</p><p>This allows your application to:</p><ul><li>Detect when a session is impersonated</li><li>Display clear UI indicators (e.g. <em>“Impersonating user”</em>)</li><li>Log actions with both <strong>actor</strong> and <strong>target user</strong></li><li>Enforce additional restrictions during impersonation</li></ul><blockquote><strong><em>Why This Beats a Custom Implementation</em></strong></blockquote><p>Rolling your own impersonation solution typically means:</p><ul><li>Manually issuing tokens</li><li>Managing parallel sessions</li><li>Handling edge cases and revocation</li><li>Building your own audit trail</li><li>Risking security flaws</li></ul><p>Keycloak solves all of this at the identity layer, with <strong>one API call</strong>, proper security enforcement, and full observability.</p><p>If impersonation is a requirement in your system, using Keycloak’s native support is not just easier , it’s <strong>significantly safer and more maintainable</strong>.</p><h3>Limitations</h3><ul><li><strong>Cross-realm impersonation:</strong> Impersonator info may appear as the master realm user. Fix by adding a custom user attribute mapped into the token.</li><li><strong>Backend-only impersonation:</strong> API calls return a redirect URL but do not set cookies; HTTP-only cookies require browser involvement.</li><li><strong>Frontend required:</strong> The redirect URL must be opened in the browser (via redirect or iframe) to finalize impersonation.</li><li><strong>Original admin session cannot be restored:</strong> Once impersonation starts, the admin’s original session ends. There’s no built-in way to revert to the old session automatically.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd305d0b7150" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Multi-Package Publishing in Monorepos with Lerna]]></title>
            <link>https://medium.com/@zainabghauri7799/simplifying-multi-package-publishing-in-monorepos-with-lerna-db1fd6fa4e33?source=rss-5a73d85d21de------2</link>
            <guid isPermaLink="false">https://medium.com/p/db1fd6fa4e33</guid>
            <category><![CDATA[yarn]]></category>
            <category><![CDATA[npm-package]]></category>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[lerna]]></category>
            <dc:creator><![CDATA[Zainab Ghauri]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 15:58:37 GMT</pubDate>
            <atom:updated>2025-02-04T16:06:40.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ej4eyZMaavLGonDkD9qtFg.jpeg" /><figcaption>Pic Courtesy — <a href="https://emmer.dev/blog/migrating-existing-repos-to-a-lerna-monorepo/">https://emmer.dev/blog/migrating-existing-repos-to-a-lerna-monorepo/</a></figcaption></figure><blockquote><strong>The Challenge and the Solution:</strong></blockquote><p>Publishing multiple packages within a monorepo manually can quickly become overwhelming. Each package requires its own version bump, a separate publish process, and individual pipelines — resulting in significant overhead and potential for error.</p><p>After conducting some research and collaborating with the team, I came across <strong>Lerna</strong> — and it was a game-changer.</p><h3>What is Lerna?</h3><p><strong>Lerna</strong> is a powerful tool designed to manage and automate tasks within a monorepo. It’s particularly useful for projects that consist of multiple packages, allowing you to easily manage versioning, dependencies, and publishing.</p><p>In short, Lerna helps teams maintain monorepos by automating tedious tasks like:</p><ul><li><strong>Versioning</strong>: Automatically bump versions of your packages based on changes.</li><li><strong>Publishing</strong>: Simplify the process of releasing multiple packages at once.</li><li><strong>Dependency Management</strong>: Track and manage internal dependencies between packages.</li></ul><p>Lerna works by understanding the relationships between packages in a monorepo and managing the complexities that arise when you need to release updates to them. It helps to keep everything in sync and makes the whole process much smoother.</p><h3>How Lerna Solves the Problem</h3><p>Lerna tackles the challenges of managing multiple packages in a monorepo head-on. Here’s how:</p><ol><li><strong>Single Command Publishing</strong><br>Before <strong><em>Lerna</em></strong>, you either had to <strong>publish each package individually</strong> or put in a lot of effort to <strong>hardcode your CI pipelines</strong> just to publish each package correctly. With <strong><em>Lerna</em></strong>, you can <strong>publish all updated packages with a single command</strong>. It automatically handles versioning and only publishes the packages that have changed — making the whole process smooth and easy</li><li><strong>Automated Versioning</strong><br>Lerna’s versioning system automatically identifies which packages need to be versioned based on code changes. Whether you use <strong>fixed versioning</strong> (where all packages share the same version) or <strong>independent versioning</strong> (with separate versions for each package), Lerna keeps everything in sync and consistent.</li><li><strong>Efficient Dependency Management</strong><br>Lerna understands the relationships between packages. If Package A depends on Package B, it ensures that Package B is published first. This dependency-aware publishing guarantees the correct order and prevents potential issues caused by out-of-sync packages</li></ol><h3>Getting Started with Lerna</h3><p>Now that we know how Lerna can simplify publishing and managing multiple packages, let’s dive into how you can set it up for your monorepo. The setup process is quick and easy, and it only takes a few steps to get everything up and running.</p><ol><li><strong>Install Lerna</strong></li></ol><p>First, install Lerna globally (or locally in your project):</p><pre>npm install --global lerna</pre><p>2. <strong>Initialize Your Monorepo</strong></p><p>If you don’t have a lerna.json file in your repo yet, run:</p><pre>npm install --global lerna</pre><p>This will set up the basic structure with a packages/ directory for your individual packages, as well as the necessary configuration files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*nLaer95W87LIUNOI0s7wig.png" /><figcaption>Pic Courtesy — Google Images</figcaption></figure><p>3. <strong>Configure Lerna for npm Workspaces</strong></p><p>We’ll configure Lerna to work with <strong>npm</strong> and enable <strong>npm Workspaces</strong> to manage dependencies across your monorepo. To do this, update your lerna.json file to look like this:</p><pre>{<br>  &quot;packages&quot;: [&quot;packages/*&quot;],<br>  &quot;version&quot;: &quot;independent&quot;,  // Independent versioning for each package<br>  &quot;npmClient&quot;: &quot;npm&quot;,        // Use npm as the package manager<br>  &quot;useWorkspaces&quot;: true      // Enable npm Workspaces<br>}</pre><p>This tells Lerna to use npm as the npmClient and enables npm Workspaces to help manage your packages and their dependencies.</p><p>4. <strong>Set Up </strong><strong>package.json for the Root Project</strong></p><p>Now, we need to configure the root package.json to use npm Workspaces and set it as <strong>private</strong> to prevent the root project from being published. Add the following to your root package.json:</p><pre>{<br>  &quot;name&quot;: &quot;my-mono-repo&quot;,<br>  &quot;private&quot;: true,<br>  &quot;workspaces&quot;: [<br>    &quot;packages/*&quot;  // Define all the packages within the &#39;packages&#39; directory<br>  ]<br>}</pre><p>The private: true flag ensures that the root project won&#39;t be accidentally published to npm.</p><p>5. <strong>Bootstrap Your Packages</strong></p><p>After setting everything up, you need to install dependencies and link internal packages. To do that, run:</p><pre>lerna bootstrap</pre><p>This will install all external dependencies and create symlinks between the local packages in the monorepo.</p><h3><strong>Publish Your Packages</strong></h3><p>Before publishing, there are a few important Lerna commands that prepare your packages and versioning for release. Here’s what you’ll typically do before hitting publish:</p><p><strong>(i) Build the Packages</strong></p><p>First, make sure everything is built and ready to go by running:</p><pre>lerna build</pre><p>This command will build all the packages in your monorepo, ensuring that the latest code is compiled and ready for publishing.</p><p><strong>(ii) Versioning the Packages</strong></p><p>Next, you’ll want to version your packages based on the changes you’ve made. To automatically bump versions, create changelogs, and ensure everything is up-to-date, run:</p><pre>lerna version --conventional-commits --no-push --yes</pre><ul><li>--conventional-commits: This flag reads your commit messages (following the <strong>Conventional Commit</strong> format) to determine the version bump (major, minor, or patch).</li><li>--no-push: Prevents Lerna from pushing changes to the remote repository automatically, in case you want to manually review or push changes later.</li><li>--yes: Skips the confirmation prompt, making the command fully automated.</li></ul><p>After running the version command, it’s always a good idea to <strong>check the versions</strong> and ensure everything looks good. You can inspect the lerna.json and package.json files to verify that the version changes are correct.</p><p><strong>(iii) Publish the Packages</strong></p><p>Once versioning is complete and you’re satisfied with the changes, it’s time to publish. The following command will publish the updated packages:</p><pre>lerna publish from-package --conventional-commits --yes</pre><ul><li>from-package: This flag ensures that only the packages with updated versions (from the versioning step) will be published.</li><li>--conventional-commits: Ensures Lerna uses the <strong>Conventional Commit</strong> strategy for versioning.</li><li>--yes: Skips the confirmation prompt to automatically publish the packages.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMOeHDcBUVgzQw2lK4mUuA.png" /><figcaption>Pic Courtesy — Google Images</figcaption></figure><p><strong>(iv) Push Changes and Tags to you Git Repo (If Needed)</strong></p><p>If you’ve used <strong>Lerna</strong> to version your packages and <strong>commit</strong> the changes, the next step is to push those changes to your Git repository. This includes the updated version numbers in your package.json files and any other changes you’ve made.</p><p>To push the changes (including the version bump) to your remote Git repository, simply run:</p><pre>git push</pre><p>However, <strong>this won’t push your tags</strong>. If you want to also push the version tags (e.g., v1.2.0), which mark the specific versions you just published, you will need to do that separately using:</p><pre>git push --tags</pre><h3>Verify the Publish using lerna</h3><p>Once your changes are pushed to both your Git repository and NPM, it’s good practice to <strong>verify</strong> that everything is working as expected. This includes:</p><ul><li><strong>Check the NPM registry</strong>: Go to the <a href="https://www.npmjs.com/">NPM website</a> and search for your package to ensure it’s been published with the correct version.</li><li><strong>Verify the changelog</strong>: Ensure that Lerna has correctly generated the changelog and version information for your packages. This will help you track the changes over time.</li></ul><h3>Common Pitfalls and Troubleshooting</h3><p>While Lerna is an incredibly powerful tool for managing monorepos, there are a few common challenges that you may run into. Here’s how to avoid or troubleshoot them:</p><h4>1. Versioning Conflicts</h4><p>One of the most common issues is versioning conflicts, especially when using <strong>independent versioning</strong>. You might accidentally try to publish a package with a version that already exists, or forget to bump the version number before publishing.</p><p><strong>How to Avoid:</strong></p><ul><li>Always check the version numbers before publishing. Lerna provides built-in checks during the lerna version process, so make sure to review the proposed version bump.</li><li>Use <strong>conventional commits</strong> to automate versioning and reduce the chances of manual errors.</li></ul><p><strong>What to Do if It Happens:</strong></p><ul><li>If you get an error like fatal: tag &#39;v1.2.0&#39; already exists, you can delete the conflicting tag locally and remotely with:</li></ul><pre>git tag -d v1.2.0<br>git push --delete origin v1.2.0</pre><ul><li>Then, run lerna version again.</li></ul><h4><strong>2. Unpublished Packages</strong></h4><p>Sometimes, packages that have been updated in the monorepo don’t get published as expected.</p><p><strong>How to Avoid:</strong></p><ul><li>Use lerna publish from-package to ensure that only updated packages are pushed to NPM.</li><li>Double-check your commit history and changelog to ensure Lerna recognizes the changes.</li></ul><p><strong>What to Do if It Happens:</strong></p><ul><li>Run lerna publish from-package --conventional-commits --yes again to push the packages that might have been missed.</li></ul><h3>Conclusion: Why Lerna is a Game-Changer for Managing Multiple Packages</h3><p>Lerna streamlines managing multiple packages in a monorepo, automating versioning, dependencies, and publishing.</p><p><strong>Key Takeaways:</strong></p><ul><li><strong>Single Command</strong>: Publish all packages with one command.</li><li><strong>Automated Versioning</strong>: Auto-bumps versions for consistency.</li><li><strong>CI/CD Integration</strong>: Automates publishing with CI/CD.</li><li><strong>Dependency Management</strong>: Manages package dependencies and order.</li></ul><p>Lerna boosts productivity, reduces overhead, and scales workflows efficiently.</p><h3>Call to Action: Try Lerna and Engage with the Community</h3><p>If you’re managing multiple packages in a monorepo or considering switching to a monorepo structure, <strong>Lerna</strong> is the tool you need to streamline your workflow. Give it a try, and see how much time it saves you!</p><ul><li><strong>Get Started</strong>: <a href="https://lerna.js.org/">Lerna Documentation</a> — Set up your project with Lerna and start automating your package management today.</li></ul><p>Let’s make managing monorepos easier, together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db1fd6fa4e33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React and GraphQL: A Complete Guide to Data Fetching and Modifying]]></title>
            <link>https://medium.com/@zainabghauri7799/react-and-graphql-a-complete-guide-to-data-fetching-and-modifying-ff8452a44a4f?source=rss-5a73d85d21de------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff8452a44a4f</guid>
            <category><![CDATA[graphql-vs-rest-api]]></category>
            <category><![CDATA[fetching-with-usequery]]></category>
            <category><![CDATA[apollo-client-in-react]]></category>
            <category><![CDATA[apollo-client-setup]]></category>
            <category><![CDATA[updating-with-usemutation]]></category>
            <dc:creator><![CDATA[Zainab Ghauri]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 15:47:29 GMT</pubDate>
            <atom:updated>2024-12-12T16:04:47.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*Py814ZLrWTlJjdclVNi2RQ.png" /></figure><p>In modern web development, data fetching and modifying can be complex. Traditional REST APIs often result in over-fetching or under-fetching data. This is where <strong>GraphQL</strong> excels — providing a more flexible, precise, and efficient approach to fetching data in React applications.</p><p>In this guide, I’ll walk you through how to seamlessly integrate <strong>GraphQL</strong> with <strong>React</strong> using <strong>Apollo Client</strong>, streamlining your data-fetching process for faster and more optimized performance.</p><h3>Why GraphQL Over REST?</h3><p>GraphQL provides a more efficient and flexible approach to data fetching than traditional REST APIs, offering several key advantages:</p><ul><li><strong>Precise Data Fetching</strong>: GraphQL allows you to specify exactly what data you need, eliminating the problems of over-fetching and under-fetching commonly encountered with REST APIs.</li><li><strong>Unified Endpoint</strong>: Unlike REST, which requires multiple endpoints for different resources, GraphQL uses a single endpoint to handle all requests, streamlining your API calls and simplifying maintenance.</li><li><strong>Real-Time Data</strong>: With GraphQL subscriptions, you can easily integrate real-time updates into your application, allowing for dynamic, interactive user experiences.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zasEpjjKzoBdCs-UdquPw.png" /></figure><h3>Setting Up Apollo Client in React</h3><p>To start using GraphQL with React, Apollo Client is the go-to solution. It simplifies interaction with a GraphQL API and provides powerful features like caching, pagination, and real-time data management. Let’s walk through setting it up:</p><ol><li><strong>Install Apollo Client</strong></li></ol><pre>npm install @apollo/client graphql</pre><p><strong>2. Initialize Apollo Client</strong></p><p>In your main index.tsx or App.tsx file, configure Apollo Client and wrap your application in the ApolloProvider:</p><pre>import { ApolloClient, InMemoryCache, ApolloProvider, gql } from &#39;@apollo/client&#39;;</pre><pre>// Apollo Client setup<br>const client = new ApolloClient({<br>  uri: &#39;https://my-test-app/graphql&#39;, // Replace with your GraphQL API URL<br>  cache: new InMemoryCache(),<br>});<br><br>ReactDOM.render(<br>  &lt;ApolloProvider client={client}&gt;<br>    &lt;App /&gt;<br>  &lt;/ApolloProvider&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><h3><strong>Fetching and Modifying Data with GraphQL in React</strong></h3><p>Now that Apollo Client is set up, let’s start fetching data and modifying! Apollo provides hooks like useQuery and useMutation to seamlessly integrate GraphQL data fetching into your React components.</p><blockquote><strong><em>1. Fetching Data with </em></strong><strong><em>useQuery</em></strong></blockquote><p>The useQuery hook in Apollo Client is used to fetch data from a GraphQL API, functioning similarly to a GET request in REST. It automatically manages the loading, error, and data states, simplifying asynchronous data fetching in React components. Instead of using axios or fetch, you use the useQuery hook to fetch the required data. For better code organization, it&#39;s a good practice to keep your GraphQL queries in a separate folder.</p><p><strong>Step by Step Example:</strong></p><ul><li><strong>Define the GraphQL Query</strong> , In our case, let’s take an example to fetch all users from a company , you will first define the gql query like:</li></ul><pre>import { gql } from &#39;@apollo/client&#39;;<br><br>export const GET_ALL_USERS_IN_COMPANY = gql`<br>  query getAllUsersInCompany($companyId: ID!) {<br>    company(id: $companyId) {<br>      name<br>      users {<br>        id<br>        name<br>        email<br>        phone<br>      }<br>    }<br>  }<br>`;</pre><ul><li><strong>Fetching data using the </strong><strong>useQuery hook in Apollo Client , </strong>It provides you with multiple built-in functions, such as data, error, loading, and refetch. These functions help manage the state of your request, allowing you to easily handle loading states, errors, and refetch data when needed. I will cover these features in more detail in another article.</li></ul><pre>const { <br>  loading : GetAllUsersInCompanyLoading, <br>  error : GetAllUsersInCompanyError, <br>  data : GetAllUsersInCompanyData,<br>  refetch: GetAllUsersInCompanyRefetch,<br>} = useQuery(GET_ALL_USERS_IN_COMPANY, { <br>  variables: { companyId } <br>});</pre><ul><li>You can use the fetched data to render on your UI screen in various ways, depending on your requirements. You can store the data in a useState hook or directly pass it to a mapping function. Here, I will show you how to directly pass the data to be rendered on your UI.</li></ul><pre>  return (<br>    &lt;Box&gt;<br>      &lt;Typography variant=&quot;h5&quot; gutterBottom&gt;<br>        Users in {GetAllUsersInCompanyData?.company?.name}<br>      &lt;/Typography&gt;<br>      &lt;List&gt;<br>        {GetAllUsersInCompanyData?.company?.users.map((user: any) =&gt; (<br>          &lt;ListItem key={user.id}&gt;<br>            &lt;ListItemText<br>              primary={&lt;strong&gt;{user.name}&lt;/strong&gt;}<br>              secondary={<br>                &lt;&gt;<br>                  &lt;div&gt;Email: {user.email}&lt;/div&gt;<br>                  &lt;div&gt;Phone: {user.phone}&lt;/div&gt;<br>                &lt;/&gt;<br>              }<br>            /&gt;<br>          &lt;/ListItem&gt;<br>        ))}<br>      &lt;/List&gt;<br>    &lt;/Box&gt;<br>  );</pre><blockquote><strong><em>2. Handling Data Modifications using</em></strong><strong><em>useMutation</em></strong></blockquote><p>In GraphQL, the useMutation hook is used to modify data on the server, like creating, updating, or deleting records—similar to POST, PUT, or DELETE in REST APIs. It offers a more flexible and efficient way to handle these operations.</p><p><strong>Step by Step Example:</strong></p><ul><li><strong>Define the GraphQL Mutation:</strong> In our case, it is to add a new user to the company. Assuming you have input type defined on your server side. let say it is:</li></ul><pre>input UserInput {<br>  name: String!<br>  email: String!<br>  phone: String!<br>}</pre><pre>import { gql } from &#39;@apollo/client&#39;;<br><br>// Define the mutation for adding a user<br>export const ADD_USER_IN_COMPANY = gql`<br>  mutation AddUser($input: UserInput!) {<br>    addUser(input: $input) {<br>      id<br>      name<br>      email<br>    }<br>  }<br>`;</pre><ul><li><strong>Performing operations with the </strong><strong>useMutation hook</strong> in Apollo Client allows you to modify data on the server. Although it doesn&#39;t include a built-in refetch function like useQuery, you can trigger data refetching manually using options like refetchQueries or onCompleted. These options help you control the flow after the mutation completes, ensuring your UI stays in sync with the latest data. I’ll explore these features in more detail in an upcoming article.</li></ul><pre>  // Use the useMutation hook<br>  const [addUser, { loading, error, data }] = useMutation(ADD_USER_IN_COMPANY, {<br>    refetchQueries: [{ query: GET_ALL_USERS_IN_COMPANY }], // Refetch the list of users after the mutation<br>    onCompleted: (data) =&gt; {<br>      console.log(&#39;User added successfully&#39;, data);<br>    }<br>  });</pre><h3><strong>Conclusion</strong></h3><p>In conclusion, integrating GraphQL with React revolutionizes how you fetch and manage data in your applications. Unlike traditional REST APIs, GraphQL empowers you to request only the data you need, eliminating issues of over-fetching and under-fetching. With Apollo Client, working with GraphQL becomes effortless, offering hooks like useQuery and useMutation to simplify data fetching and updates. Apollo Client also brings powerful features like automatic cache management, error handling, and real-time updates, making your React apps more responsive and efficient. Whether you&#39;re building simple apps or complex systems, this combination provides a seamless, high-performance solution for modern web development.</p><h3>Limitation</h3><p>GraphQL provides powerful features, but there are two key limitations to consider:</p><ol><li><strong>Increased Complexity</strong>: For simple applications, GraphQL can add unnecessary complexity, especially when managing intricate queries and schema.</li><li><strong>Cache Management</strong>: Although Apollo Client offers caching, keeping the cache in sync after mutations or complex updates can be challenging and require additional effort.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff8452a44a4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>