40% of Firebase User Registrations Missing Firestore Documents

40% of Firebase User Registrations Missing Firestore Documents

I’m experiencing a critical issue with my NextJS/Firebase application where approximately 40% of random user registrations result in “orphaned” users – users that exist in Firebase Authentication but have no corresponding document in Firestore.

The issue occurs randomly with no consistent pattern or error messages:

  1. Users are 100% successfully created in Firebase Authentication
  2. But approximately 40% of random registration attempts fail to create the Firestore document
  3. No errors are thrown during this process
  4. Affected users see a “User not approved” error on our Login form
  5. These users can’t get their pending registrations approved from the admin side because our app checks for Firestore documents

Code

Here’s my user registration function in AuthContext.js:

// New user registration
const register = async (email, password, userData) => {
  setErrorMessage('');
  let user = null;
  
  try {
    setLoading(true);
    
    // 1. Create user in Firebase Auth
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    user = userCredential.user;
    
    // 2. Create user document data
    const userDocData = {
      email: email,
      name: userData.name || '',
      surname: userData.surname || '',
      phone: userData.phone || '',
      role: userData.role || 'student',
      status: 'pending',
      createdAt: serverTimestamp(),
      updatedAt: serverTimestamp(),
      package: userData.role === 'student' ? {
        remainingClasses: 0,
        paymentStatus: false
      } : null
    };
    
    // 3. Create document in Firestore
    const batch = writeBatch(db);
    batch.set(doc(db, 'users', user.uid), userDocData);
    await batch.commit();
    
    // 4. Verify document creation
    const checkDoc = await getDoc(doc(db, 'users', user.uid));
    if (!checkDoc.exists()) {
      throw new Error('User document was not created');
    }
    
    // 5. Logout after successful registration
    await signOut(auth);
    
    return user;
    
  } catch (error) {
    // If Auth user created but Firestore document failed, delete Auth user
    if (user) {
      try {
        // Try to delete any partially created document
        try {
          await deleteDoc(doc(db, 'users', user.uid));
        } catch (docError) {
          console.error("Error deleting document:", docError);
        }
        
        // Delete Auth user
        await deleteUser(user);
      } catch (deleteError) {
        console.error('Error deleting user after failed registration:', deleteError);
      }
    }
    
    // Handle specific errors
    switch (error.code) {
      case 'auth/email-already-in-use':
        setErrorMessage('Αυτή η διεύθυνση email χρησιμοποιείται ήδη.');
        break;
      case 'auth/invalid-email':
        setErrorMessage('Μη έγκυρη διεύθυνση email.');
        break;
      case 'auth/weak-password':
        setErrorMessage('Ο κωδικός πρέπει να έχει τουλάχιστον 6 χαρακτήρες.');
        break;
      default:
        setErrorMessage('Σφάλμα κατά την εγγραφή. Παρακαλώ δοκιμάστε ξανά.');
        break;
    }
    throw error;
  } finally {
    setLoading(false);
  }
};

I’ve also tried implementing a retry mechanism with exponential backoff:

// 3. Create document with retry mechanism
let success = false;
let attempts = 0;

while (!success && attempts < 5) {
  try {
    attempts++;
    console.log(`Attempt ${attempts} to create Firestore document`);
    
    const batch = writeBatch(db);
    batch.set(doc(db, 'users', user.uid), userDocData);
    await batch.commit();
    
    // Immediate verification
    const checkDoc = await getDoc(doc(db, 'users', user.uid));
    if (checkDoc.exists()) {
      success = true;
      console.log(`Successfully created Firestore document on attempt ${attempts}`);
    } else {
      console.warn(`Document check failed after batch commit (attempt ${attempts})`);
      // Wait before retrying (exponential backoff)
      await new Promise(resolve => setTimeout(resolve, 1000 * attempts));
    }
  } catch (error) {
    console.error(`Firestore error on attempt ${attempts}:`, error);
    // Wait before retrying
    await new Promise(resolve => setTimeout(resolve, 1000 * attempts));
  }
}

if (!success) {
  throw new Error(`Failed to create Firestore document after ${attempts} attempts`);
}

I’ve also implemented a temporary workaround in onAuthStateChanged:

useEffect(() => {
  const unsubscribe = onAuthStateChanged(auth, async (user) => {
    if (user) {
      try {
        // Check if document exists
        const userDoc = await getDoc(doc(db, 'users', user.uid));
        
        // If document doesn't exist, create it (fix orphaned users)
        if (!userDoc.exists()) {
          console.log("Orphaned user detected. Synchronizing...");
          
          await setDoc(doc(db, 'users', user.uid), {
            email: user.email,
            name: '',
            surname: '',
            phone: '',
            role: 'student',
            status: 'pending',
            createdAt: serverTimestamp(),
            updatedAt: serverTimestamp(),
            package: {
              remainingClasses: 0,
              paymentStatus: false
            }
          });
          
          // Continue with normal checks...
        }
      } catch (error) {
        console.error('Error fetching user data:', error);
        setCurrentUser(null);
      }
    } else {
      setCurrentUser(null);
    }
    setLoading(false);
  });

  return () => unsubscribe();
}, [auth, db, router]);

What I’ve Tried

  1. Using writeBatch instead of setDoc – same issue occurs
  2. Adding a retry mechanism with up to 5 attempts – still fails occasionally
  3. Adding verification after document creation – confirms document isn’t being created
  4. Adding proper cleanup to delete orphaned Authentication users
  5. Adding detailed logging – no errors appear in logs when the issue occurs

Environment

  • NextJS 14
  • Firebase v9
  • Using the client SDK
  • Using the initialization pattern with singleton instance

Question

What could be causing this inconsistent behavior where Firebase Auth users are created but Firestore documents fail silently ~40% of the time? I need a reliable solution as this affects a significant portion of our user registrations.

Is there a way to ensure atomicity between Auth and Firestore operations? Would using Firebase Cloud Functions for user creation provide better reliability?

How to design an online , low-cost face-recognition attendance system for rural schools? [closed]

We’re building an attendance web-app for rural schools (mobile-first). Requirements: client-side face recognition, local storage syncs when online, works on low-end phones/laptops monolingual( English) UI, CSV export, privacy (face embeddings stored locally). What libraries/approach do you recommend for reliable offline face recognition and local storage (IndexedDB/SQLite/PWA)?Thanks!
Important:
my team (6 members) has no programming or web-tech experience — none of us know HTML, CSS, or JavaScript. We need beginner-friendly, low-effort options.

We are complete beginners with no prior programming or web development experience. This is our very first project, and we are building it as part of Smart India Hackathon 2025. We are still learning and exploring the right tools and approaches.

Problem in registry template xml with javascript in odoo

I new to odoo and created an ADDON in odoo V17 where I am consulting the holiday assignments of an employee, to show each record on the main screen of the Personal Time calendar, however I have a problem, it generates an xml file in which I create a template to traverse the list and render it, for this I have a JS file in which I consult the function that brings me the list and in which I register the template, I have another xml in the inheritance of hr_holidays.TimeOffDashboard to insert the code section of the template, but I always get this error

Here error:

OwlError: An error occured in the owl lifecycle (see this Error's "cause" property) Error: An error 
occured in the owl lifecycle (see this Error's "cause" property) at handleError 
(http://localhost:8069/web/assets/debug/web.assets_web.js:9193:35) (/web/static/lib/owl/owl.js:1633) at 
App.handleError (http://localhost:8069/web/assets/debug/web.assets_web.js:13590:20) 
(/web/static/lib/owl/owl.js:6030) at Fiber._render 
(http://localhost:8069/web/assets/debug/web.assets_web.js:9346:30) (/web/static/lib/owl/owl.js:1786) at 
Fiber.render (http://localhost:8069/web/assets/debug/web.assets_web.js:9335:18) 
(/web/static/lib/owl/owl.js:1775) at ComponentNode.initiateRender 
(http://localhost:8069/web/assets/debug/web.assets_web.js:10015:23) (/web/static/lib/owl/owl.js:2455)

Caused by: TypeError: Cannot read properties of undefined (reading 'name') at TimeOffDashboard.template 
(eval at compile (http://localhost:8069/web/assets/debug/web.assets_web.js:13312:20), <anonymous>:30:47) 
(/web/static/lib/owl/owl.js:5752) at Fiber._render 
(http://localhost:8069/web/assets/debug/web.assets_web.js:9343:38) (/web/static/lib/owl/owl.js:1783) at 
Fiber.render (http://localhost:8069/web/assets/debug/web.assets_web.js:9335:18) 
(/web/static/lib/owl/owl.js:1775) at ComponentNode.initiateRender 
(http://localhost:8069/web/assets/debug/web.assets_web.js:10015:23) (/web/static/lib/owl/owl.js:2455)

JS
/** @odoo-module **/

import { Component, onWillStart, useState, xml } from "@odoo/owl";
import { useService } from "@web/core/utils/hooks";
import { registry } from "@web/core/registry";

export class CustomDashboardTimeOffCard extends Component {
    
    setup() {
        this.orm = useService("orm");
        this.user = useService("user");

        this.state = useState({
            employeeId: null,
            allocationsData: [],
        });

        onWillStart(async () => {
            const employee = await this.orm.call(
                "hr.employee",
                "search_read",
                [[["user_id", "=", this.user.userId]]],
                { limit: 1, fields: ["id"] }
            );
            if (employee.length > 0) {
                this.state.employeeId = employee[0].id;
                const allocations = await this.orm.call(
                    "hr.leave.type",
                    "get_detailed_allocations_data_request",
                    [this.state.employeeId]
                );
                this.state.allocationsData = allocations;
            }
        });
    }
}

CustomDashboardTimeOffCard.template = "hr_personal_time_automator.CustomDashboardTimeOffCard";




registry.category("components").add("hr_personal_time_automator.CustomDashboardTimeOffCard", {
    Component: CustomDashboardTimeOffCard,
});

template XML

<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
  <t t-name="hr_personal_time_automator.CustomDashboardTimeOffCard" owl="1">
    <t t-if="state.allocationsData and state.allocationsData.length > 0">
      <div class="d-flex px-4 py-2 pt-4 pb-3">
        <h4>ASIG</h4>
        <t t-foreach="state.allocationsData" t-as="alloc" t-key="alloc.id">
          <div class="text-center gap-1 px-2" style="color: #71639e;">
            <div><strong><t t-esc="alloc.name"/>: </strong></div>
            <div style="font-size: 18px; font-weight: 700;">
              <img style="width:25px;" src="miicon"/>
              <t t-esc="alloc.remaining_days"/>
            </div>
            <div style="font-size: 10px;">
              (VALIDO HASTA: <t t-esc="alloc.end_date"/>)
            </div>
          </div>
        </t>
      </div>
    </t>
    <t t-else="">
      <p>Cargando datos...</p>
    </t>
  </t>
</templates>

XML inherit TimeOffDashboard

<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
    <t t-inherit="hr_holidays.TimeOffDashboard" t-inherit-mode="extension">
        <xpath expr="//div[hasclass('o_timeoff_card')]" position="inside">
            <t t-component="CustomDashboardTimeOffCard"/>
        </xpath>
    </t>
</templates>

manifest el orden de assets

 "depends": ["base", "web", "hr_holidays", "hr", "mail"],
    "data": [],
    "assets": {
        "web.assets_backend": [ 
            "hr_personal_time_automator/static/src/xml/custom_dashboard_time_off_card.xml", 
                 "hr_personal_time_automator/static/src/js/custom_dashboard_time_off_card.js", 
            "hr_personal_time_automator/static/src/xml/time_off_dashboard_extend.xml", 
            "hr_personal_time_automator/static/src/css/hide_allocation_button.css"
            
        ],
    },

Lazy routing do not work in Angular 20, it came into ERROR RuntimeError: NG04002

I am developing an Angular application, and the version did not work as I wish. I’ve got multiple modules in this app and I used the lazy routing. But when I tried to navigate to sub module’s route, but it failed with ERROR RuntimeError: NG04002: Cannot match any routes. URL Segment: ‘pageList’. I wondered why. Here is my code.

I have got App module, Console module, and Login module. Here is some key codes:

  1. app.html
<router-outlet></router-outlet>
  1. app.routes.ts
import { Routes } from '@angular/router';
import { Login } from './login/login/login';
import { Console } from './console/console/console';

export const routes: Routes = [
    { path: '', pathMatch: 'full', redirectTo: '/login' },
    { path: 'login', component: Login, loadChildren: () => import('./login/login-module').then(m => m.LoginModule) },
    { path: 'console', component: Console, loadChildren: () => import('./console/console-module').then(m => m.ConsoleModule) },
    
];
  1. app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection } from '@angular/core';
import { PreloadAllModules, provideRouter, RouteReuseStrategy, withPreloading } from '@angular/router';

import { routes } from './app.routes';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { SimpleReuseStrategy } from './console/SimpleReuseStrategy';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(),
    provideBrowserGlobalErrorListeners(),
    provideZonelessChangeDetection(),
    provideRouter(routes,withPreloading(PreloadAllModules)), 
    provideClientHydration(withEventReplay()), 
    { 
      provide: RouteReuseStrategy, useClass: SimpleReuseStrategy 
    }
  ]
};
  1. console-routing-module.ts
import { NgModule } from '@angular/core';
import { Router, RouterModule, Routes } from '@angular/router';
import { PageList } from './page-list/page-list';
import { Console } from './console/console';
import { CreatePage } from './create-page/create-page';
import { WordList } from './word-list/word-list';

const routes: Routes = [{
    path: 'console', component: Console,
    children: [
        { path: '', redirectTo: 'createPage', pathMatch: 'full' },
        { path: 'createPage', component: CreatePage, data: { keep: true, key: 'createPage' } },
        { path: 'pageList', component: PageList, data: { keep: true, key: 'pageList' } },
        { path: 'wordList', component: WordList, data: { keep: true, key: 'wordList' } },
        { path: '**', component: CreatePage }
    ]
}];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class ConsoleRoutingModule { 

    constructor(private router:Router) {
        console.log(this.router.config);

    }

    ngOnInit() {
        
    }
}
  1. console-module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ConsoleRoutingModule } from './console-routing-module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatNativeDateModule } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSelectModule } from '@angular/material/select';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { Console } from './console/console';
import { PageList } from './page-list/page-list';
import { CreatePage } from './create-page/create-page';
import { Router } from '@angular/router';

@NgModule({
  declarations: [Console, PageList, CreatePage],
  imports: [
    CommonModule, MatButtonModule, MatMenuModule, MatDividerModule, MatIconModule, MatSnackBarModule, MatSelectModule, MatDatepickerModule, MatNativeDateModule, MatPaginatorModule,
    MatButtonModule, MatMenuModule, MatSelectModule,
    MatDatepickerModule, MatPaginatorModule, MatSnackBarModule,
    MatDividerModule, MatIconModule,

    FormsModule, ReactiveFormsModule,
    ConsoleRoutingModule
  ]
})
export class ConsoleModule {

  constructor(private router: Router) {
    
  }

  ngOnInit() {
    
  }

 }
  1. console.html
<div style="width: 100vw;display: flex;margin: 0 auto;">
    <!---左边菜单栏-->
    <div
        style="width: 200px;height: 100vh;background-color: white;border-left: 1px solid #ddd;border-right: 1px solid #ddd;overflow-y: auto;">
        <p class="menuSection">文章</p>
        <p [ngStyle]="{'background-color': menuText==='createPage' || menuText==='createPage'?'#eee':'white'}" class="menuItem" (click)="onMenuClick('createPage')">写文章</p>
        <p [ngStyle]="{'background-color': menuText==='pageList'?'#eee':'white'}" class="menuItem" (click)="onMenuClick('pageList')">文章列表</p>

        <p class="menuSection">单词</p>
        <p [ngStyle]="{'background-color': menuText==='wordList'?'#eee':'white'}" class="menuItem"
            (click)="onMenuClick('wordList')">单词列表</p>
    </div>
    <!---右边内容栏-->
    <div class="rightOutlet">
        <router-outlet></router-outlet>
    </div>

</div>
  1. console.ts
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-console',
  //imports: [CommonModule, RouterModule, RouterOutlet],
  standalone:false,
  templateUrl: './console.html',
  styleUrl: './console.scss'
})
export class Console {

  private router = inject(Router);

  menuText: string = 'createPage';
  onMenuClick(text: string) {
    this.menuText = text;
    this.router.navigate(['../' + this.menuText])
  }
}

8.page-list.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-page-list',
  standalone:false,
  //imports: [],
  templateUrl: './page-list.html',
  styleUrl: './page-list.scss'
})
export class PageList {

}

The architecture of project is bellow:
[project architecture][1]
[1]: https://i.sstatic.net/1Kqiskm3.png

How can I improve Wix website loading speed by optimizing custom code and scripts? [closed]

.I am running a business website on Wix, and I noticed that the loading speed is slower than expected.
Since most of my visitors come from mobile devices, I want to optimize performance as much as possible.

I already tried:

  • Compressing images inside Wix,
  • Reducing the number of installed apps,
  • Using Wix’s built-in performance settings.

But the website still takes more than 6 seconds to load.

I want to know if there are ways to use custom code or developer tools in Wix to improve loading speed.
For example:

  • Can I manually add JavaScript for lazy loading of images?
  • Is it possible to optimize or defer Wix’s default CSS/JS files?
  • Any proven coding techniques that can reduce render-blocking resources in Wix?

Any suggestions or code examples for optimizing Wix website performance through scripts or custom code would be very helpful.

How do arguments and return values flow between functions in JavaScript? [closed]

I am a newbie. I have been learning javascript and I feel like I almost grasp it but I am a very visual learner and I am having trouble visualizing how this works. I am learning with code academy. My ultimate goal is to understand how inputs and outputs are inserted into reusable functions.

I understand the general idea, but I get lost in the details of how the argument flows through or is ‘passed’ to the functions.

My specific questions are:

  • When I call getFahrenheit(15), where exactly is the ’15’ passed to?
  • In getFahrenheit(celsius), the argument is named ‘celsius’. Does ’15’ replace ‘celsius’ inside that function, and then get passed into multiplyByNineFifths()?
  • In multiplyByNineFifths(number), does ’15’ replace ‘number’, so the second line becomes return 15 * (9/5);?
  • When multiplyByNineFifths() returns ’27’, does that mean the call inside getFahrenheit(celsius) effectively becomes 27 + 32?
  • Finally, does the code re-run both functions again, or is it just passing the returned value along?

The code below is a snippet example that I have questions about. No setup or context needed. This is the exact code I want to make sure I understand how it works.

function multiplyByNineFifths(number) {
  return number * (9/5);
};

function getFahrenheit(celsius) {
  return multiplyByNineFifths(celsius) + 32;
};

getFahrenheit(15); // Returns 59

I think my confusion is mostly about whether the return value actually “replaces” the function call inside the other function, or whether something else is happening behind the scenes.

I have tried googling my question and have not been able to find the answer. I googled “how do helper functions in javascript work?” I have found several questions about helper functions (like what they do, how they can improve readability of code, etc.), but none that explain how a code like this works. I am just looking for some helping clarifying how the inputs and outputs visually flow through when the getFahrenheit(15) function is called. I also read all ‘similarly phrased questions’ and do not see an on point explanation.

User script append to DOM without having to reload page

I am working on a user script (I’m using Tampermoney as my user script manager) to append a dynamic Rotten Tomatoes link to a Jellyfin movies/series page.

It works when I manually reload on the title’s page, but I want it work when I navigate to the page without a need for a manual reload.

Here’s the effect (when reloaded currently):

User script inserts a Rotten Tomatoes link

Here is my script:

// ==UserScript==
// @name         Rotten Tomatoes Links for Jellyfin
// @namespace    http://stpettersen.xyz
// @version      2025-09-07
// @description  This script adds a Rotten Tomatoes link for TV and movies on Jellyfin.
// @author       Sam Saint-Pettersen
// @match        https://jellyfin.mmedia.stpettersen.xyz/*
// @icon         https://www.rottentomatoes.com/assets/pizza-pie/images/favicon.ico
// @grant        none
// ==/UserScript==

(function() {
    // Replace @match with your Jellyfin server URL.
    'use strict';

    function waitForElement(selector, targetNode = document.body) {
        return new Promise((resolve) => {
            const element = document.querySelector(selector);
            if (element) {
                return resolve(element);
            }

            const observer = new MutationObserver(() => {
            const foundElement = document.querySelector(selector);
            if (foundElement) {
                observer.disconnect();
                resolve(foundElement);
            }
    });

    observer.observe(targetNode, {
      childList: true,
      subtree: true
    });
  });
}

function injectRTLink() {
    let targetEl = null;
    let links = document.getElementsByClassName('button-link')
    for (let i = 0; i < links.length; i++) {
        if (links[i].href.startsWith("https://www.themoviedb.org")) {
            targetEl = links[i];
            break;
        }
        if (targetEl != null) {
            break;
        }
    }
    let genre = "m";
    let year = "";
    let title = document.getElementsByTagName("bdi")[0].innerHTML.toLowerCase()
    .replace(/ /g,"_").replace(/'/g,"").replace(/_&amp;/g, "").replace(/:/g, "").replace(/,/g, "").replace(/-/g, "_");
    let otm = document.getElementsByClassName("originalTitle")[0];
    if (otm) {
        let ot = document.getElementsByClassName("originalTitle")[0].innerHTML;
        if (ot.length > 0) year = "_" + ot;
    }
    let ott = document.getElementsByClassName("originalTitle")[0];
    if (ott) {
        let ot = document.getElementsByClassName("originalTitle")[0].innerHTML;
        if (ot == "TV") genre = "tv";
    }
    targetEl.insertAdjacentHTML("afterend",
    `, <a id="rt-link" target="_blank" class="button-link emby-button" href="https://www.rottentomatoes.com/${genre}/${title}${year}">Rotten Tomatoes</a>`
    .replace("_TV", ""));
}

// Wait for bottom cards to load before attempting to get/insert links.
waitForElement('.card').then(element => {
    injectRTLink();
});
})();

Any pointers would be great. Thank you.

Chart.js how to draw mixed bar width without space between bars?

I need to draw a bar chart, not exactly but somewhat similar, like in the first picture.
I have one stacked bar consisting of 2 bars one narrow bar and one nonstacked with the same width as the stacked bar.

I don´t want to have any space between them.
When I play around with barPercentage and categoryPercentage I only get spaces around the narrow bar.

This is what I want:

enter image description here

And this is the only thing I can reproduce:

enter image description here

With this code:

const ctx = document.getElementById('capacityOverviewChart').getContext('2d');
const data = {
  datasets: [{
      label: 'Stacked A1',
      data: [{
        x: 'Mon',
        y: 10
      }, {
        x: 'Tue',
        y: 12
      }, {
        x: 'Wed',
        y: 8
      }, {
        x: 'Thu',
        y: 14
      }],
      backgroundColor: 'rgba(255, 99, 132, 0.6)',
      stack: 'stack1',
      barPercentage: 1.0,
      categoryPercentage: 0.8,
    },
    {
      label: 'Stacked A2',
      data: [{
        x: 'Mon',
        y: 15
      }, {
        x: 'Tue',
        y: 18
      }, {
        x: 'Wed',
        y: 12
      }, {
        x: 'Thu',
        y: 20
      }],
      backgroundColor: 'rgba(255, 159, 64, 0.6)',
      stack: 'stack1',
      barPercentage: 1.0,
      categoryPercentage: 0.8,
    },
    {
      label: 'Narrow B',
      data: [{
        x: 'Mon',
        y: 20
      }, {
        x: 'Tue',
        y: 18
      }, {
        x: 'Wed',
        y: 22
      }, {
        x: 'Thu',
        y: 16
      }],
      backgroundColor: 'rgba(75, 192, 192, 0.6)',
      stack: 'stack2',
      barPercentage: 1, // ~1/6th width
      categoryPercentage: 0.2,
    },
    {
      label: 'Normal C',
      data: [{
        x: 'Mon',
        y: 25
      }, {
        x: 'Tue',
        y: 30
      }, {
        x: 'Wed',
        y: 28
      }, {
        x: 'Thu',
        y: 32
      }],
      backgroundColor: 'rgba(54, 162, 235, 0.6)',
      stack: 'stack3',
      barPercentage: 1.0,
      categoryPercentage: 0.8
    }
  ]
};

const config = {
  type: 'bar',
  data: data,
  options: {
    responsive: true,
    plugins: {
      legend: {
        display: false
      },
    },
    scales: {
      x: {
        stacked: true,
        ticks: {
          display: true
        },
      },
      y: {
        stacked: false,
        beginAtZero: true,
      }
    }
  }
};

new Chart(ctx, config);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="capacityOverviewChart">

Why is frameLocator used in Playwright to locate components within the iframe?

I want to locate a button which is in an iframe. To do so, I need to use the weird iframe notation:

page.locator('iframe[name="some_iframe_id"]').contentFrame().locator('#some_locator')

On the other hand, locating the same component on a page without an iframe is way simpler:

page.locator('#some_locator')

Why is it not possible to use the usual notation and why do I need to refer which iframe specifically to use? Shouldn’t Playwright be able to figure this out on its own?

When to choose Typescript over Javascript? [closed]

We are busy with adding new features to Dragon1.

We have clients with large volume JSON files and some RAW data is with and without quotes and stuff. No that structured.

As CTO I am still doing coding once a week.

Some of my team members say we should let go of javascript and move to typescript.

But I need better arguments than I have heard so far.

Who has some good arguments.

We have done some comparison experiments on APIs and data conversions and javascript seems to be faster and less strict, which is easier for prototyping.

for instance this:

         const data = [
          { id: 1, value: 100 },
          { id: 2, value: '200' }, // This would cause a TS error
          { id: 3, value: 300 }
         ];

         const transformedData = data.map(item => ({
           id: item.id,
           // This line works because JS is flexible
           transformedValue: item.value * 2
          }));


          console.log(transformedData);
          // Output: [ { id: 1, transformedValue: 200 }, { id: 2, transformedValue: 400 }, { id: 3, transformedValue: 600 } ]

How to properly lift any container on pressing the input bar in newer Android version and older version all devices? (KeyboardAvoidingView)

Very simple question.

I have pixel 6a below code works everywhere expect the real pixel device 6a which has android 16.

It works on Redmi note 11 which has android 11 and on Emulator which is pixel 6 (android 14). But not on the pixel device. When I use the below code

<KeyboardAvoidingView
  behavior={Platform.OS === 'ios' ? 'padding' : undefined}
  style={{ flex: 1 }}
  enabled
>

Sometimes the container goes up but just up to the input bar, only input bar gets hidden. But meanwhile when I turn off the screen and unlock my pixel 6a mobile, it gets corrected. I just want a global solution, can anyone help. I don’t know what is happening when turning off and on the screen.

This is my current code. It works but with a bug like gaps being produced often. But works but not smoothly.

const keyboardOffset = isKeyboardVisible ?  headerHeight : headerHeight + insets.bottom + 23;
  
  return (
    <KeyboardAvoidingView
    keyboardVerticalOffset={keyboardOffset}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      style={{ flex: 1 }}
      enabled
    >
      <SafeAreaView style={styles.container}>
        {/* Header */}
        <View style={styles.header}></View>
        <FlatList />
        <MessageInput receiverUsername={selectedReceiverUsername || ''} status={status} />
      </SafeAreaView>
    </KeyboardAvoidingView>
  )

Using RTK Query to create a library for calls to my API

I have a REST API that I want to call from multiple React projects, and I was thinking to make a library that exposes the REST API calls, using the Redux Toolkit Query code generation.

I would like to let individual projects specify a base URL (as there are several API versions) and a custom function to get a user token, but I could not find a way to make this co-exist with the generated code.

The idea would be something along these lines:

import { myApi } from "./myApi";
import { fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const createMyApi = (baseUrl, getTokenFunction) => {
  
  const newBaseQuery = fetchBaseQuery({
    baseUrl,
    prepareHeaders: (headers) => {
      headers.set("Authorization", `Bearer ${getTokenFunction()}`);
      return headers;
    },
  });
  
  return ??? // return a version of the generated 'myApi' that uses newBaseQuery
};

Is this possible at all?

Text Cut Off and Extra Spacing When Exporting HTML to PDF with html2pdf

When exporting my HTML content to PDF using html2pdf, the text inside the element appears cut off and there is an unusually large space between elements. Specifically:

Inline-block elements (<span> and <p>) do not render correctly.

The <p> text seems cropped vertically, likely due to line-height or the way html2canvas calculates height.

Extra spacing appears around the elements, even though margin and padding are set to 0.

    const element = document.querySelector("#GGG");
    // Clone the element
    var clonedElement = element;
    clonedElement.style.display = "block";
    

    // Define the options for exporting
    const options = {
      margin: 0,
      padding:0,
      filename: filename,
      image: { type: "jpeg", quality: 1 },
      html2canvas: {
        scale: 4,
        useCORS: true,
        scrollX: 0,
        scrollY: 0,
        backgroundColor: null,
      },
      jsPDF: {
        unit: "pt",
        format: "a4",
        orientation: "portrait",
      },
      pagebreak: {
        mode: ["css", "legacy"],
      },
    };


    // Export to PDF
    html2pdf()
      .set(options)
      .from(clonedElement).outputPdf('bloburl').then((pdfUrl)=> {
        window.open(pdfUrl,'_blank');
      }).catch(e=>{
        console.log("error")
      });
    <div id="GGG">
    <span className="bg-black w-4 h-4 inline-block"></span>
    <p className="w-4 h-4 inline-block" style={{lineHeight:"100%"}}>GG</p>
    </div>

in HTML :

enter image description here

in PDF FILE :

enter image description here