Controlling modal using custom hook does not work properly

I want to render Modal.tsx in MyInfoPage.tsx(or anywhere I want to show modal).
So, I created simple custom hook useModal.ts to control isOpenModal.
But, I encountered some rendering problem.
When I try to close modal using closeModal() in Modal.tsx‘s backdrop div tag, there is any change!
More clearly, setIsOpenModal(false) in closeModal() which implemented in useModal.ts does not work…
Oddly, only setIsOpenModal doesn’t work! Other code like console.log() does work!
I’m very confused about why only setIsOpenModal(false) statement doesn’t work.
What’s wrong with this code? What concept am I confusing?

// MyInfoPage.tsx

// ...import... //

function MyInfoPage(props: MyInfoPageProps) {
  // ... //

  const { isOpenModal, openModal, closeModal } = useModal();

  const cancelClickHandler = () => {
    openModal();
  };

  const pageBackHandler = () => {
    closeModal();
    router.back();
  };

  return (
    <section className={styles.section}>
      {isOpenModal && (
        <Modal>
          <div>
            <button onClick={pageBackHandler}>Yes</button>
            <button onClick={closeModal}>No</button>
          </div>
        </Modal>
      )}

      // .... //
    </section>
  );
}

export default MyInfoPage;
// Modal.tsx

// ...import... //

function Modal(props: ModalProps) {
  const { closeModal } = useModal();

  const content = (
    <>
      <div className={styles.backdrop} onClick={closeModal}></div>
      <div className={styles.modal_body}>
        <div>{props.children}</div>
      </div>
    </>
  );

  return createPortal(content, document.getElementById("modal") as HTMLElement);
}

export default Modal;
// useModal.ts

// ...import... //

interface UseModalHook {
  isOpenModal: boolean;
  openModal: () => void;
  closeModal: () => void;
}

function useModal(): UseModalHook {
  const [isOpenModal, setIsOpenModal] = useState(false);

  const openModal = () => {
    setIsOpenModal(true);
  };

  const closeModal = () => {
    setIsOpenModal(false);
  };

  return { isOpenModal, openModal, closeModal };
}

export default useModal;

TypeORM, set default select attributes for an entity

I have an entity with an attribute isCanceled. I want the records with isCanceled = true to be ignored unless I specifically query them.

example:

@Entity()
export class Request {
  ...other props

  @Column()
  isCanceled: boolean;
}

I thought about extending the find and findOne methods, but I am not sure if it will take effect in relations, like here.

const user = User.findOne({ where: { id: 1 }, relations: { requests: true } })

Printing data with Thermal printer (TSC TTP 244 pro)

I am creating a table whose QR is also ready and showing it as you can see in the mentioned image(https://i.stack.imgur.com/XyERO.png)
Using these method:-

const data = [["1.3","NORMAL OD","FINOTEX","5376","13.040"],["1.3","NORMAL OD","FINOTEX","5376","13.040"],["1.3","NORMAL OD","FINOTEX","5376","13.040"],["1.3","NORMAL OD","FINOTEX","5376","13.040"]]

    let table = `<table border="1">

       <thead>

       <tr>

       <th>Size</th>

       <th>OD</th>

       <th>Brand</th>

       <th>Weight</th>

       </tr>

       </thead>

     <tbody>`;

        let total_weight = 0;

        data.forEach(element => {

total_weight += parseFloat(element[3]);

            table += `

            <tr>

          <td>${element[0]}</td>

          <td>${element[1]}</td>

          <td>${element[2]}</td>

          <td>${parseFloat(element[3])}</td>

          </tr>

                      `

                    });

             table += `

             <tr>

          <td colspan=3>Total Weight</td><td>${total_weight}</td>

           </tr>

           </tbody>

           </table>

                       `       

       

             document.getElementById('table').innerHTML = table;

The problem is:-
I have a TSC TTP 244 Pro printer. I want to print this entire div (table and qr code both) using this printer as shown in the image with size = 75mm×50mm

I haven’t not tried yet anything because I have not idea about thermal printer

document.getElementById() returns null in Chrome extension

I’m trying to make Chrome extension…

my popup.html has

<textarea id="userData" name="userData" rows="10" cols="20">test</textarea>
<button id="doit" type="button">Do it!</button>

and my popup.js has

document.getElementById("userData").value = 'xxx';

const doit_btn = document.getElementById('doit');

doit_btn.addEventListener('click', async () => {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: load_data
    });
});

function load_json() {
    console.log('load_data() is running...');
    document.getElementById("userData").value = 'yyy';
}

The getElementById("userData") in the root works, text area value gets set. But when I lick the button I do get load_data() is running... in the console, but then an error that the document.getElementById("userData") is null and it can’t get it’s value.

why?

How am i supposed to get data from an xml returned by a website?

Okay, im losing my mind here, so, it’s simple

I wanna get the xml that this website is returning with javascript (or jquery)

this is the website: https://wswhomo.afip.gov.ar/wsfev1/service.asmx?WSDL

Ive been trying basically everything and getting in the deep ass rabbit hole and found no actual way to just get the data with javascript that doesnt involve get a whole ass server running on the back …

The info is there, you can see it when you go into, i just wanna the plain text at this point tbh, if i can get that it would be more than enough because with jscript i can get the data i need even from the plain text…

is it possible to make the html children div element width not greater than than the parent element

I have a html div called pdfContainer that shows pdf content in webpage. The pdf rend html look like this:

<div id="pdfContainer" className={styles.previewBody} onScroll={(e) => handlePdfScroll(e)}>
            <Document options={options}
                file={curPdfUrl}
                onLoadSuccess={onDocumentLoadSuccess}>
                {renderPages(numPages)}
            </Document>
</div>

this is the previewBody css define:

.previewBody {
    flex-grow: 1;
    background-color: rgb(233, 233, 233);
    display: flex;
    overflow: scroll;
    justify-content: center;
}

this is how to render the pdf pages:

const renderPages = (totalPageNum: number | undefined) => {
        if (!totalPageNum || totalPageNum < 1) return;
        const tagList: JSX.Element[] = [];
        for (let i = 1; i <= totalPageNum; i++) {
            tagList.push(
                <Page key={i}
                    className={styles.pdfPage}
                    scale={projAttribute.pdfScale}
                    onLoad={handlePageChange}
                    canvasRef={(element) => updateRefArray(i, element)}
                    onChange={handlePageChange}
                    onRenderSuccess={handlePageRenderSuccess}
                    pageNumber={i} >
                    {curPdfPosition && viewport ? <Highlight position={curPdfPosition}
                        pageNumber={i}
                        viewport={viewport}></Highlight> : <div></div>}
                </Page>
            );
        }
        return tagList;
    }

this is the pdfPage define:

.pdfPage {
    width: auto;
    margin-bottom: 5px;
}

Now I am facing the issue that the Document page’s width will greater than the parent element pdfContainer.

enter image description here

what should I do to let the children pdf page not greater than the parent? BTW, the pdfContainer is draggale enabled by left/right, the pdfContainer width will change when user drag the column to left or right.

Why Swiper Slider navigation (arrows) don’t work correct in my WordPress website?

I use Swiper Slider on my WordPress website.
All code (html, js and css) is converted to a shortcode with a code snippet plugin.
Everything is working fine and the slider is fine, but there is one problem!
The problem is that the arrows or navigations are not showing properly and I want to fix it.
(I show you this problem with red arrows in the picture).

<link rel="stylesheet" href=".../swiper/swiper-bundle.min.css" />
<script src=".../swiper/swiper-bundle.min.js"></script>

<!-- Swiper -->
  <div class="swiper mySwiper">
    <div class="swiper-wrapper">
        <div class="swiper-slide"><a href="#" rel="noopener"><img src=".../slider/s11.webp" /></a></div>
        <div class="swiper-slide"><a href="#" rel="noopener"><img src=".../slider/s22.webp" /></a></div>
        <div class="swiper-slide"><a href="#" rel="noopener"><img src=".../slider/s33.webp" /></a></div>
    </div>
    <div class="swiper-button-next"></div>
    <div class="swiper-button-prev"></div>
    <div class="swiper-pagination"></div>
  </div>

  <script>
    var swiper = new Swiper(".mySwiper", {
      spaceBetween: 10,
      centeredSlides: true,
      loop: true,
      effect: "fade",
      autoplay: {
        delay: 5000,
        disableOnInteraction: false,
      },
      pagination: {
        el: ".swiper-pagination",
        clickable: true,
      },
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
    });
  </script>

<style>
    .swiper {
      width: 100%;
      height: auto;
    }

    .swiper-slide {
      text-align: center;
      font-size: 18px;
      background: #fff;
      display: block;
      justify-content: center;
      align-items: center;
      border-radius: 0;
    }

    .swiper-slide img {
      display: block;
      width: 100%;
      height: auto;
      object-fit: cover;
      border-radius: 0;
    }
    
</style>

image description

When I put the codes in the html file, it works properly, but when I put it in my WordPress site, it doesn’t work properly.

Getting an error when notifying Html Css Js

HTML :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="nofitication_area_gonderen" id="nofitication_area_gonderen">
        <span class="nofitication_area_gonderen_top_bar">
            <label class="nofitication_area_gonderen_top_bar_lbl" id="nofitication_area_gonderen_top_bar_lbl">Notification</label>
        </span>
        
        <span  class="nofitication_area_gonderen_label" id="nofitication_area_gonderen_label"></span>
    </div>

    <button id="click_btn">Click Here</button>

    <script src="script.js"></script>
</body>
</html>

CSS :


.nofitication_area_gonderen{
    position: absolute;
    width: 341px;
    height: 83px;
    top: 48px;
    left: 790px;
    flex-shrink: 0;
    background: rgba(19, 20, 20, 0.76);
}
.nofitication_area_gonderen_top_bar{
    position: absolute;
    width: 341px;
    height: 26px;
    top: 0px;
    flex-shrink: 0;
    background: rgba(19, 20, 20, 0.88);
}

.nofitication_area_gonderen_top_bar_lbl{
    position: relative;
    left: 10px;
    top: 3px;
    
    color: #689BFF;
    font-family: 'Be Vietnam Pro', sans-serif;
    font-size: 15px;
    font-style: normal;
    font-weight: 500;
    line-height: 141%; /* 0px */
}
.nofitication_area_gonderen_label{
    position: absolute;
    top: 26px;
    height: 57px;
    width: 341px;
    display: flex;
    text-align: center;
    align-items: center;
    justify-content: center; 

    color: #ffffff;
    font-family: 'Be Vietnam Pro', sans-serif;
    font-size: 13px;
    font-style: normal;
    font-weight: 200;
    line-height: 141%; /* 0px */
}


.slideIn {
    -webkit-animation-name: slideInDown;
    animation-name: slideInDown;
    -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
    }
    @-webkit-keyframes slideInDown {
    0% {
    -webkit-transform: translateY(-100%);
    transform: translateY(-100%);
    visibility: visible;
    }
    100% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
    }
    }
    @keyframes slideInDown {
    0% {
    -webkit-transform: translateY(-100%);
    transform: translateY(-100%);
    visibility: visible;
    }
    100% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
    }
}


/* style.css */
.slideOutUp {
    -webkit-animation-name: slideOutUp;
    animation-name: slideOutUp;
    -webkit-animation-duration: 0.4s;
    animation-duration: 0.4s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
  }
  
  @-webkit-keyframes slideOutUp {
    0% {
      -webkit-transform: translateY(0);
      transform: translateY(0);
    }
    100% {
      visibility: hidden;
      -webkit-transform: translateY(-100%);
      transform: translateY(-160%);
    }
  }
  
  @keyframes slideOutUp {
    0% {
      -webkit-transform: translateY(0);
      transform: translateY(0);
    }
    100% {
      visibility: hidden;
      -webkit-transform: translateY(-100%);
      transform: translateY(-160%);
    }
  }

JS :

function Notify(NotifyTime) {
    var myElement = document.getElementById('nofitication_area_gonderen');
    myElement.classList.add('slideIn');

    document.getElementById("nofitication_area_gonderen_label").innerHTML = '<span> Test <span style="color: yellow;"> Notify </span> </span>';


    setTimeout(() => {
        myElement.classList.add('slideOutUp');
        setTimeout(() => {
            myElement.classList.remove('slideOutUp');
        }, 400);
    }, NotifyTime);
}

document.getElementById("click_btn").addEventListener("click",function() {
    Notify(2500)
});

There is an error in the code here. The problem is that the notify window appears on the screen when I press the button, there is no problem. But then it gets stuck on the screen.
What I want is this:
Every time I press the button, the notify window appears on the screen, and if I press the button again, the notify window is reset and appears on the screen again. So, every time I press the button, the nottify window appears on the screen from scratch.

If anyone has any ideas on how I can do it, I would be very happy to help. Thanks in advance <3

I tried many ways to solve this problem, but I could not find a solution.

lexical scope in Javascript issue

in the following code snippet, I defined “bob” first, but the output is “alice:1 hi alice”, I don’t know why?

let user = "";
function greet() {
  console.count(user);
  return `hi ${user}`;
}
user = "bob";
user = "alice";
console.log(greet());//alice:1 hi alice

Usage of Async await with hooks

I have a simple translation function that takes one parameter(string) and return string. It works fine when i use like await translation(key) how ever my need it to use it frequently inside in react native component like below

<Text>{tranlate("faqs")}</Text>

Then again somewhere

<Button title={translate("terms")}/>

My question is although its a async function and not trigger without await or then/catch block. What could be other way i can simple use it without await or then/catch because using it like below is not working

<Text>{await translate("faqs")}</Text>

Any help would be really appriciated!Thanks

fix available via `npm audit fix` is not working

Hello i am runing npm i mysql but i get follow error:

up to date, audited 323 packages in 2s

35 packages are looking for funding run npm fund for details

1 low severity vulnerability

To address all issues, run: npm audit fix

After I run npm audit fix I get:

sweetalert2 >=11.6.14 sweetalert2 v11.6.14 and above contains
potentially undesirable behavior –
https://github.com/advisories/GHSA-mrr8-v49w-3333
fix available via
npm audit fix node_modules/sweetalert2

I tired to run : npm uninstall sweetalert2, also update but still getting same error.
I am not able to solved this by runin a npm audit fix. Could anyone please help me?

RichUtils.toggleInlineStyle(editorState, “style”) is not working (DRAFT.JS)

import React, { useState } from "react";
import { Editor, EditorState, RichUtils } from "draft-js";

const DraftEditor = () => {
  const [editorState, setEditorState] = useState(() =>
    EditorState.createEmpty()
  );

  const styleMap = {
    RED: {
      color: "red",
    },
    CODE: {
      backgroundColor: "yellow",
    },
  };

  const handleBeforeInput = (e, editorState) => {
    const selection = editorState.getSelection();
    const contentState = editorState.getCurrentContent();
    const currentBlock = contentState.getBlockForKey(selection.getStartKey());
    const currentText = currentBlock.getText();
    const endText = currentText.slice(-4);

    // Check if the "*" character is followed by a space
    if (e === " " && currentText.endsWith("*") && !endText.includes("**")) {
      console.log("* character followed by space!");
      setEditorState(RichUtils.toggleInlineStyle(editorState, "BOLD"));
    }
    // Check if the "**" character is followed by a space
    if (e === " " && currentText.endsWith("**") && !endText.includes("***")) {
      console.log("** character followed by space!");
      setEditorState(RichUtils.toggleInlineStyle(editorState, "RED"));
    }
    // Check if the "***" character is followed by a space
    if (e === " " && endText.endsWith("***")) {
      console.log("*** character followed by space!");
      setEditorState(RichUtils.toggleInlineStyle(editorState, "UNDERLINE"));
    }
    // Check if the "```" character is followed by a space
    if (e === " " && endText.endsWith("```")) {
      console.log("``` character followed by space!");
      setEditorState(RichUtils.toggleInlineStyle(editorState, "CODE"));
    }
    // Check if the "#" character is followed by a space
    if (e === " " && endText.endsWith("#")) {
      console.log("# character followed by space!");
      setEditorState(RichUtils.toggleBlockType(editorState, "header-one"));
    }
  };

  return (
    <div id="draft-editor">
      <div
        style={{
          display: "flex",
          flexDirection: "row",
          justifyContent: "space-between",
        }}
      >
        <div />
        <h3>Demo Editor by Ujjwal Sharma</h3>
        <button className="button">Save</button>
      </div>
      <Editor
        editorState={editorState}
        customStyleMap={styleMap}
        onChange={setEditorState}
        handleBeforeInput={(e, editorState) => {
          handleBeforeInput(e, editorState);
        }}
      />
    </div>
  );
};

export default DraftEditor;

PS: if i hit the same line setEditorState(RichUtils.toggleInlineStyle(editorState, "CODE")) onClick of a button where event.preventDefault() is present then the inlinestyles changes

I am trying to change inline styles of the editor on basis of the key pressed and wrote the code for it but block type is changing but not inline styles

i am trying to do is if “* ” is pressed then code should become BOLD and similarly other functonalities mentioned in the if else

Error: Page “/api/auth/[…nextauth]” is missing “generateStaticParams()” so it cannot be used with “output: export” config

I am working on Next.js project in which I have implemented user authentication using
next-auth and Google Provider. When I am trying to create the build for the project the the complier throws this error “Error: Page “/api/auth/[…nextauth]” is missing “generateStaticParams()” so it cannot be used with “output: export” config.”
This is my api > auth > […nextauth] > route.js file

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google"

export const authoptions = {
    providers : [
        GoogleProvider({
            clientId : process.env.GOOGLE_CLIENT_ID,
            clientSecret : process.env.GOOGLE_CLIENT_SECRET
        })
    ],
    secret : process.env.NEXTAUTH_SECRET,
    callbacks : {
        async redirect(){
            return process.env.NEXTAUTH_URL;
        }
    }
}

const handler = NextAuth(authoptions)

export {handler as GET, handler as POST}

This is my code for api > auth > […nextauth] > route.js file

/** @type {import('next').NextConfig} */
const nextConfig = {
    output : "export"
}

module.exports = nextConfig

This my code for next.config.js file