useEffect and promise priority in inital and subsequent renders

I have below code and help me to find the output with accurate explanation.

'infiniteLoopProtection:false'
import * as React from "react";
import { useState, useEffect } from "react";
import { createRoot } from "react-dom/client";
import { screen, fireEvent } from "@testing-library/dom";

function App() {
  const [state, setState] = useState(0)
  console.log(1)
  
  const start = Date.now()
  while (Date.now() - start < 50) {
    window.timestamp = Date.now()
  }

  useEffect(() => {
    console.log(2)
  }, [state])

  Promise.resolve().then(() => console.log(3))

  setTimeout(() => console.log(4), 0)

  const onClick = () => {
    console.log(5)
    setState(num => num + 1)
    console.log(6)
  }
  return <div>
    <button onClick={onClick}>click me</button>
  </div>
}

const root = createRoot(document.getElementById('root'));
root.render(<App/>)

setTimeout(() => fireEvent.click(screen.getByText('click me')), 100)

Now I am confused how this can be.
Que: How promise and setTimeOut functions are executing before useEffect on initial render but after useEffect on subsequent render?

I tried running it on codeSandbox and got the below output

1
2
3
4
5
6
1
2
3
4

Even I executed the code in codeSandBox and got the same output. But https://bigfrontend.dev/react-quiz/useeffect-timing-iii is not accepting this answer. According to them correct answer should be

1
3
4
2
5
6
1
2
3
4

Recurisve components select active aelement

I made a recursive component in vue that shows a tree structure.I’m trying to add an active class to the element that is clicked but I can’t reset the selection when I click a new element.

This is the father component

<div class="tree-menu-links">
       <ul class="tree-menu-links">
          <tree-menu
          :label="PP.tree.label"
          :nodes="PP.tree.nodes"
          :depth="0"
          :expand-all="expandAll"
          :selected="PP.tree.selected"
          @reset-selection="resetSelection"
      ></tree-menu>
   </ul>
</div>

and this is the Tree-Menu component

<template>
  <li>
    <ul class="tree-ul">
      <div
        @click="toggleChildren"
        :class="{ 'tree-item': true, active: selectedElement }"
      >
        <!-- <div :style="indent" @click="toggleChildren" class="tree-item"></div> -->
        <v-icon
          class="tree-icon"
          v-if="nodes"
          :icon="
            !showChildren && !expandAll
              ? 'mdi-plus-circle-outline'
              : 'mdi-minus-circle-outline'
          "
        ></v-icon>

        <div>
          <span
            @click="selectElement(nodes)"
            class="tree-span"
            :style="[{ color }, showChildren ? { fontWeight: 'bold' } : {}]"
            >{{ label }}</span
          >
        </div>
        <!-- <span
          class="tree-span"
          :style="[{ color }, showChildren ? { fontWeight: 'bold' } : {}]"
          >{{ label }}</span
        > -->
      </div>

      <tree-menu
        v-if="showChildren || expandAll"
        v-for="(node, index) in nodes"
        :index="index"
        :key="node.label"
        :nodes="node.nodes"
        :label="node.label"
        :color="node.color"
        :depth="depth + 1"
        :expand-all="expandAll"
        :selected="node.selected"
        @reset-selection="resetSelection"
      ></tree-menu>
    </ul>
  </li>
</template>

<script setup>

const props = defineProps({
  label: String,
  color: String,
  nodes: Array,
  index: Number,
  depth: {
    type: Number,
    default: 0,
  },
  expandAll: Boolean,
  selected: Boolean,
});

const checkedNodes = ref(props.nodes);
const selectedElement = ref(props.selected);

const resetSelection = (nodes) => {
  selectedElement.value = false;
  checkedNodes.value.forEach((node) => {
    node.selected = false;
  });
};

function toggleChildren() {
  showChildren.value = !showChildren.value;
  //selectedElement.value = !selectedElement.value;
  emit("reset-selection");
}

Any idea?

I tried using emit to pass the result of the reset selection method but the previous element is not resetting

How to fix the remaining height issue?

Here is the reference image with space below I am using Playwright to convert the (jinja template) HTML file to pdf, where I have to fix the issue that if the content is less than one page, I have to add that extra row of the remaining height. Still, I am getting an issue: it always leaves some space below even after calculating the remaining height. As we can see after the bank details section below it leaves a blank space. I am adding js to calculate the remaining height

let pageHeight = document.body.getBoundingClientRect().height;
      let contentHeight = document
        .querySelector(".main-table")
        .getBoundingClientRect().height;
let remainingHeight = Math.round(pageHeight - contentHeight);
 if (contentHeight < pageHeight) {        
        addHeightRow(remainingHeight, "Remaining");
        document.querySelector(".section-6").style.borderBottom = "none";
      }
function addHeightRow(height, label) {
      const lineItems = document.querySelectorAll(".line-item");
      lineItems.forEach((lineItem, index) => {
        if (index === lineItems.length - 1) {
          lineItem.insertAdjacentHTML(
            "afterend",
            `
              <tr class="remaining-height-row" style="height: ${height}px;">
                  <td class="border-right border-bottom sr-no text-center"></td>
                  <td class="border-right border-bottom des-of-goods"></td>
                  <td class="border-right border-bottom qty right">${height}</td>
                  <td class="border-right border-bottom unit right"></td>
                  <td class="border-right border-bottom rate right"></td>
                  <td class="border-right border-bottom discount right"></td>
                  <td class="border-right border-bottom discount-amt right"></td>
                  <td class="border-bottom tax-amt right"></td>
              </tr>
            `
          );
        }
      });
    }

i have tried calculating it in the python file too but still got nothing

from jinja2 import Template
from playwright.sync_api import sync_playwright


def create_playwright_invoice_pdf(html_content, pdf_path, data: dict):
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()
        # page.set_content(html_content)
        page.set_content(html_content, wait_until='networkidle')

        page.evaluate("""
        () => {
            function setEqualRowHeights() {
                const taxTable = document.querySelector(
                    ".section-4-wrapper .tax-table table"
                );
                const allTotalSect = document.querySelector(
                    ".section-4-wrapper .all-total-count"
                );
                const allTotalSectTotalInfo = document.querySelector(
                    ".section-4-wrapper .all-total-count .total-info"
                );
                const rows = document.querySelectorAll(
                    ".line-item-table tbody tr.line-item"
                );
                const section = document.querySelector(".section-4");

                const taxTableHeight = taxTable.getBoundingClientRect().height;
                const allTotalSectTotalInfoHeight =
                    allTotalSectTotalInfo.getBoundingClientRect().height;

                if (taxTableHeight > allTotalSectTotalInfoHeight) {
                    taxTable.style.borderBottom = "1px solid black";
                    allTotalSect.style.borderBottom = "1px solid black";
                } else {
                    section.style.borderBottom = "1px solid black";
                }

                let pageHeight = document.body.getBoundingClientRect().height;
                let contentHeight = document
                    .querySelector(".main-table")
                    .getBoundingClientRect().height;
                const section1 = document
                    .querySelector(".section-1")
                    .getBoundingClientRect().height;
                const section2 = document
                    .querySelector(".section-2")
                    .getBoundingClientRect().height;
                const section3 = document
                    .querySelector(".section-3")
                    .getBoundingClientRect().height;
                const section4 = document
                    .querySelector(".section-4")
                    .getBoundingClientRect().height;
                const section5 = document
                    .querySelector(".section-5")
                    .getBoundingClientRect().height;
                const section6 = document
                    .querySelector(".section-6")
                    .getBoundingClientRect().height;
                const tableHeadingHeight = document
                    .querySelector(".table-heading")
                    .getBoundingClientRect().height;
                const lineItemTotal = document
                    .querySelector(".line-item-total")
                    .getBoundingClientRect().height;
                const lineItems = document.querySelectorAll(".line-item");
                const totalSection3Height =
                    section1 + section2 + section3 - lineItemTotal;
                const totalLastSectionHeight =
                    section4 + section5 + section6 + lineItemTotal;

                let remainingHeight = Math.round(pageHeight - contentHeight);

                if (contentHeight < pageHeight) {
                    addHeightRow(remainingHeight, "Remaining");
                }

                return remainingHeight;
            }

            function addHeightRow(height, label) {
                const lineItems = document.querySelectorAll(".line-item");
                lineItems.forEach((lineItem, index) => {
                    if (index === lineItems.length - 1) {
                        lineItem.insertAdjacentHTML(
                            "afterend",
                            `
                            <tr class="remaining-height-row" style="height: ${height}px;">
                                <td class="border-right border-bottom sr-no text-center"></td>
                                <td class="border-right border-bottom des-of-goods"></td>
                                <td class="border-right border-bottom qty right">${height}</td>
                                <td class="border-right border-bottom unit right"></td>
                                <td class="border-right border-bottom rate right"></td>
                                <td class="border-right border-bottom discount right"></td>
                                <td class="border-right border-bottom discount-amt right"></td>
                                <td class="border-bottom tax-amt right"></td>
                            </tr>
                            `
                        );
                    }
                });
            }

            return setEqualRowHeights();
        }
        """)
        header_template = """  
                <style> 
                header {
                    width: 100%;
                    font-size: 10px;
                    font-family: "Times New Roman", sans-serif;
                    margin: 0 1cm 10px 1cm;
                    box-sizing: border-box;
                }
                .date {
                    text-align: right;
                    width: 100%;
                }
            </style>
            <header>
                <div class="date"></div>
            </header>
        """

        footer_template = """
                <style>
                    .footer {
                        font-size: 10px;
                        text-align: center;
                        width: 100%;
                        margin: 0 1cm 0 1cm;
                        font-family: "Times New Roman", sans-serif;
                    }
                    .footer-content {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        width: 100%;
                        height: 100%;
                    }
                    .fw-bold {
                        font-weight: bold;
                    }
                </style>
                        <div class="footer">
                        <div class="footer-content">
                        <p class="fw-bold">Powered By TECHstile.in</p>
                        <p>This is a Computer Generated Invoice</p>
                        <p>{{invoice_number}}-
                        <strong><span class="pageNumber"></span>/<span class="totalPages"></span></strong>
                        </p>
                        </div>
                </div>
            """
        template = Template(footer_template)
        rendered_footer = template.render(invoice_number=data['invoice_number'])

        page.pdf(path=pdf_path, prefer_css_page_size=False,
                 format='A4',
                 margin={'top': '1cm', 'right': '1cm', 'bottom': '1.2cm', 'left': '1cm'},
                 display_header_footer=True,
                 header_template=header_template,
                 footer_template=rendered_footer)
        browser.close()

I have ERROR after clic on button with function

I have button who do functin
Function:

methods: {
        addToCard(object) {
                    object = this.objects[isAdded];
                if (!object == false) {
                    console.log("isAdded");
                    object.isAdded = true;
                } else {
                    console.log("is not Added");
                    object.isAdded = false;
                }
        }
    }
};

And data objects:

    data() {
        return {
            objects: [
                { text: "test", price: 50, ImgUrl: "/images.png", isAdded: false },
                { text: "test2", price: 60, ImgUrl: "/images.png", isAdded: false },
                { text: "test3", price: 70, ImgUrl: "/images.png", isAdded: false },
                { text: "test4", price: 80, ImgUrl: "/images.png", isAdded: false },
                { text: "test5", price: 90, ImgUrl: "/images.png", isAdded: false },
            ],
        };
    },

when I click on the button <Button @click="addToCard(object)">add</Button>
I have a Error in console

Uncaught TypeError: _ctx.addToCard is not a function
    NuxtJS 4
        0
        callWithErrorHandling
        callWithAsyncErrorHandling
        invoker

I did read MDN web docs but I don’t find what I need

Calling all array items [0,1,2,3] BESIDES an item specified [e.g. 3] using index

I need to remove all buttons except the one which was clicked (perhaps using e.target.id?) – according to its index (using for loop.

I tried to create variable and declared it let buttonsX = buttons[i] so I could refer to it later in the if statement as !buttonsX and then it would call all the array buttons EXCEPT the button with the current index (triggered by a mousedown event).

But nothing happened.

I read there are the pull() & splice() functions but they would just require unnecessary lines of code that could’ve been prevented by a smaller code.

Other than them – I haven’t found any resources about such a function on the internet.

Also, it must be pure javascript,

Thank you very much.

TypeError: Cannot read properties of null (reading ‘map’);

function stableSort(array, comparator) {
    const stabilizedThis = array.map((el, index) => [el, index]);
    stabilizedThis.sort((a, b) => {
        const order = comparator(a[0], b[0]);
        if (order !== 0) {
            return order;
        }
        return a[1] - b[1];
    });
    return stabilizedThis.map((el) => el[0]);
}

in need to test this by using jest explain me

give me the test case

Event listeners are removed from TextBox when it loses focus

I’m working with event listeners on an asp.net TextBox and they do work fine until it loses focus. Once it does that it seems that event listeners are removed and they don’t fire at all as noted by the absence of logging in the console. My code should mask input text after 3rd character and ensure the cursor is positioned always at the end of text. Is there any way to reattach the listeners?

document.addEventListener("DOMContentLoaded", function() {

  let node = document.getElementById('TxtAccountName');
  let hidden = document.getElementById('HFAccName');

  node.addEventListener('keydown', function(e) {

    console.log("Fired the keydown event")
    //compares the cursorPosition to the length of text

    if (node.selectionStart !== node.value.length) {
      e.preventDefault();
      positionAtEndOfText();
    }
  });

  node.addEventListener('keyup', function(e) {  
    console.log("Fired keyup event")

    let text = node.value;
    if (text.length > 3) {
      node.value = text.substring(0, 3) + '*'.repeat(text.length - 3);
    }
  });

  node.addEventListener('input', function() {
    console.log("Fired input event")

    if (node.selectionStart !== node.value.length) {
      e.preventDefault();
      positionAtEndOfText();
    }
  });
});



function positionAtEndOfText() {

  let text = node.value;

  node.focus();



  if (node.setSelectionRange) {

    node.setSelectionRange(text.length, text.length);

  } else if (node.createTextRange) {

    let range = node.createTextRange();

    range.collapse(true)

    range.moveEnd('character', value.length)

    range.moveStart('character', value.length)

    range.select()

  }

}
<input id="TxtAccountName">
<input id="HFAccName">

I tried having a ‘focus’ event but apparently it didn’t work.

Nextjs Server-side redirect not working when deployed to AWS

I have this server side page component. It basically takes the result of the api response and the redirects accordingly. Everything works as expected on local but as soon as i deploy it to our UAT environment on aws the redirect URL isn’t updating as if it’s never entering the try/catch the final redirect is the one still set outside the try catch block.

import VerifyEmailPageBody from "@/app/(body)/register/VerifyEmailPageBody";
import { notFound, redirect } from "next/navigation";

import { RequestRegisterUserConfirmFetch } from "@/api/services/registerUserServer.api";


const VerifyEmailPage = async ({
  searchParams,
}: {
  searchParams?: { [key: string]: string | string[] | undefined };
}) => {
  const code = searchParams?.code;
  const email = searchParams?.email;
  const expirationTime = searchParams?.expirationTime;

  if (!code) {
    return <VerifyEmailPageBody />;
  }

  const redirectPath =
    "/register/expired?email=" + encodeURIComponent(email as string);

  if (expirationTime) {
    const currentEpochTime = Math.floor(Date.now() / 1000);
    if (currentEpochTime > Number(expirationTime)) {
      return redirect(redirectPath);
    }
  }

  let redirectPathVerify: string = "/register/verify";

  try {
    // check token request
    await RequestRegisterUserConfirmFetch({
      secureToken: (code as string) || "",
    });

    redirectPathVerify = "/register/success/";

  } catch (err: unknown) {
    const errorStatus = (err as Record<string, { status: number }>)?.response
      ?.status;

    if (errorStatus === 410) {
      redirectPathVerify = redirectPath;
    }

    if (errorStatus === 500) {
      redirectPathVerify = "/login/";
    }
    return notFound();
  } finally {
    return redirect(redirectPathVerify);
  }
};

export default VerifyEmailPage;

The api call

"use server";

import { IRequestRegisterUserConfirm } from "@/api/types/registerUser.types";
import { ENV_CONSTANTS } from "@/common/constants/env.const";

export async function RequestRegisterUserConfirmFetch(
  secureToken: IRequestRegisterUserConfirm,
) {
  const baseUrl = "user/registration";
  const response = await fetch(
    `${ENV_CONSTANTS.API_BASEURL}${baseUrl}/confirmation`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${ENV_CONSTANTS.DEFAULT_API_BEARER_TOKEN}`,
        "Content-Type": "application/json",
      },
      cache: "no-store",
      body: JSON.stringify(secureToken),
    },
  );

  console.log(response);
  if (response.status === 202) {
    return { status: 202 };
  }

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return response;
}

I’ve tried it on local and it works as expected but when deployed to AWS it doesn’t work as expected

How to Remove / Delete image dynamically on click X button in ReactJS TypeScript?

I want to delete an up loaded image on the click of button, so any idea for delete image

This is my UI section



<IconButton sx={{ color: '#EBC047' }} onClick={handleRemoveImage}>
                    <Iconify icon="material-symbols:close" />
                  </IconButton>
<img
id="imageElement"
src={previewwhatsappImage || ''}
alt=""
style={{ objectFit: 'cover' }}
>

This is logic for performing operation. I tried this code block functionality to perform operation.

const handleRemoveImage = () => {
     try {
       // Clear the sessionStorage
       sessionStorage.setItem(fileSaveImage.whatsapp, previewwhatsappImage,);
       sessionStorage.removeItem(fileSaveImage.whatsapp);
       sessionStorage.clear();
       // Clear the preview image and the file state
       setPreviewWhatsappImage((prev: any) => ({ ...prev, whatsapp: '' }));
       SetFileSaveImage((prev: any) => ({ ...prev, whatsapp: '' }));
       console.log('Image removed successfully.');
     } catch (error) {
       console.error('Failed to remove image from localStorage:', error);
     }
   };

This are some code block used in this feature

uploadCommunicationCampaignWhatsappImage is the API for POST image

const { uploadCommunicationCampaignWhatsappImage } = useApiPost();

const handleSave = async (typeForButton: string) => {
    let errorCheck: boolean = false;
    const data = {
      senderId: values.sendCampaign,
      message: values.whatsapptxt,
      file: 'null',
    };

    const formData = new FormData();
    formData.append('clientCode', user?.clientCode);
    formData.append('programIdentifier', user?.programs[0]?.key);
    formData.append('userName', 'sysadmin');
    formData.append('templateId', 'null');
    // eslint-disable-next-line no-unneeded-ternary
    formData.append('campaignId', paramsId ? paramsId : createCampRespo);
    formData.append('step', 'WHATSAPP');
    formData.append(
      'banner',
      fileSaveImage.whatsapp !== '' ? fileSaveImage.whatsapp : new Blob([])
    );
    formData.append('data', JSON.stringify(data));
    if (
      values.sendCampaign === undefined ||
      values.sendCampaign === null ||
      values.sendCampaign === ''
    ) {
      errorCheck = true;
      setError('sendCampaign', { type: 'custom', message: 'Sending Campaign From is required' });
    }

    if (
      values.whatsapptxt === undefined ||
      values.whatsapptxt === null ||
      values.whatsapptxt === ''
    ) {
      errorCheck = true;
      setError('whatsapptxt', { type: 'custom', message: 'WhatsApp Message is required' });
    }

    if (!errorCheck && !disableWithoutActive(values)) {
      setLinearProgress(true);
      try {
        const response = await uploadCommunicationCampaignWhatsappImage(formData);
        if (response.responseCode === '200' || response.responseCode === 200) {
          setLinearProgress(false);
          if (typeForButton === 'save') {
            navigate('/campaigns');
          } else {
            handleNext();
          }
        }
      } catch (error) {
        console.log('error', error);
      }
    }
    if (disableWithoutActive(values) && typeForButton === 'save') {
      navigate('/campaigns');
    }
    if (disableWithoutActive(values)) {
      handleNext();
    }
  };


<IconButton sx={{ color: '#EBC047' }} onClick={handleRemoveImage}>
  <Iconify icon="material-symbols:close" />
</IconButton> 
                  <CardMedia
                    sx={{
                      height: '100%',
                      backgroundSize: 'cover',
                      backgroundRepeat: 'no-repeat',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                    component="picture"
                  >
                    <source src={previewwhatsappImage || ''} />
                    <img src={previewwhatsappImage || ''} alt="" style={{ objectFit: 'cover' }} />
                  </CardMedia>

Help me to implement this feature

Obtaining URL of page with basic authentication in Firefox

I have a page which requires Basic Authentication – for example https://authenticationtest.com/HTTPAuth/. What I want is to obtain the URL of this page before the users enter their credentials.

In Chrome I am able to do this via both the extension (chrome.tabs.query -> tabs[0].url) and via pure javascript (window.location). In Firefox however both information displays “about:newtab”.

Is there something I’m missing when it comes to pages with Basic Authentication in firefox?

I’ve tried to search the web for a related problem but I couldn’t find any.

I’m expecting to obtain the URL (in the example given authenticationtest.com/HTTPAuth) in some way just like in the case of Chrome.

Enabling frames mode in Chrome Developer Tools

I was learning how to use chrome developer tools to improve performance and debug sites and stumbled on a video about it.
The video mentions frames mode which looked pretty useful but I was not able to find any reference to it anywhere on the internet.

Ref: https://youtu.be/0xx_dkv9DEY?t=319
Note: Video from 2014, uses an older version of chrome dev tools

  • Searching chrome dev tools documentation
  • Looking for the feature on forums ( stackoverflow, reddit )
  • Messing with the settings of chrome dev tools on my machine

I was expecting there to be an option to switch to frames mode.