basic-ftp moduleHas anyone managed to use webpack or Parcel with

I have tried using webpack 5 and Parcel to build the new .js files.
The javascript file before conversion works fine with node in the command prompt but I cannot get it to work in Windows (11). I am using the latest basic-ftp 5.0.4.

Uncaught TypeError: The "original" argument must be of type Function
at promisify (util.js:614:11)
at 5u8Fu.c4216f9df743e6cc (Client.js:17:38)
at newRequire (index.47c005a7.js:71:24)
at localRequire (index.47c005a7.js:84:35)
at 2uKas.b1c576accb3ceae3 (index.js:21:14)
at newRequire (index.47c005a7.js:71:24)
at localRequire (index.47c005a7.js:84:35)
at 8Duvb.44a9388bb99fc836 (index1.js:7:16)
at newRequire (index.47c005a7.js:71:24)
at index.47c005a7.js:122:5

The error I get in the browser using Webpack or Parcel is

The index1.js File I use is

` // src/index1.js
// works with node index1.js but not with webpack
//import style from “./main.css”;

console.log("Starting");
// see https://www.npmjs.com/package/basic-ftp
const Client = require("basic-ftp")
//import * as Client from "basic-ftp"

//console.log(Client);
example();

async function example() {
const client = new Client.Client()
client.ftp.verbose = true
try {
await client.access({
host: "somehost",
user: "username",
password: "password",
secure: false
})
console.log(await client.list())
//await client.uploadFrom("README.md", "README_FTP.md")
//await client.downloadTo("README_COPY.md", "README_FTP.md")
}
catch(err) {
console.log(err) 
}
client.close()
}

//import ftp from "basic-ftp";
console.log("Finished!");

`

My package.json is as follows:

{
"name": "parcel-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"source": "src/index.html",
"scripts": {
"start": "parcel",
"build": "parcel build"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"buffer": "^6.0.3",
"node": "^21.2.0",
"parcel": "^2.10.3"
},
"dependencies": {
"basic-ftp": "^5.0.4"
}
}


My npm list is as follows:
[email protected] C:UsersgeorgDocumentsjscriptparcel-demo
+– [email protected]
+– [email protected]
+– [email protected] extraneous
+– [email protected]
`– [email protected]

Any help would be appreciated.

Node.js program using knex and google cloud sql connector doesnt exit

const Knex = require('knex');
const { Connector } = require('@google-cloud/cloud-sql-connector');


const connectWithConnector = async () => {
    const connector = new Connector();
    const clientOpts = await connector.getOptions({
        instanceConnectionName: "my-instance-connection-name",
        ipType: 'PUBLIC',
    });
    const dbConfig = {
        client: 'pg',
        connection: {
            ...clientOpts,
            user: 'my-user',
            password: 'my-user-password',
            database: 'my-database',
        }
    };

    return Knex(dbConfig);
};

const useDatabase = async () => {
    try {
        const databaseKnex = await connectWithConnector();


        console.log('Destroy');

        await databaseKnex.destroy();
    } catch (error) {
        console.error('Error:', error);
    }
};

useDatabase();

I tried write it multiple ways, but everytime process doesn’t finish after executing this code. Please help. I want to connect to Google Cloud SQL using knex. It seems like destroy() isn’t working

making variables in event listener to use in seprate if statment

So I have 2 inputs that a user must fill out to unlock the submit button. Once the inputs are filled out correctly it removes the disabled attribute from the submit button. Also I thought using let would make it a global var?:

{
  let emailunlock = false;//this cant be seen unless I add it below
}

Im assuming it dont work because its not a global variable, is there a way to use the above code to turn it into one. So that the IF and statement can see it? without modify the code too much? or am i doing something else wrong? im assuming this should be enough code its javascript

document.getElementById("cinfo").addEventListener("keyup", function() {
  var phoneInput = document.getElementById('cinfo').value;
  var phoneno = /^(?([1]{1})?[(-. )]?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if (phoneInput.match(phoneno)) {
    document.getElementById("req").innerHTML = "Thank You";
    let phoneunlock = true;
  } else {
    document.getElementById("req").innerHTML = "Amost Done";
    let phoneunlock = false;

  }
});

document.getElementById("emailinput").addEventListener("keyup", function() {
  var emailInput = document.getElementById('emailinput').value;
  var emailpat = /[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,3}$/;
  if (emailInput.match(emailpat)) {
    document.getElementById("reqqq").innerHTML = "Thank You";
    let emailunlock = true;
  } else {
    document.getElementById("reqqq").innerHTML = "Amost Done";
    let emailunlock = false;
  }
});

var emailunlock = true; // want to remove this and let the above event listener dictate the values
var phoneunlock = true; //I want to remove this and let the above event listener dictate the values

document.getElementById("cinfo").addEventListener("keyup", function() {
  if (phoneunlock && emailunlock) {
    alert('yes it did');
    document.getElementById('saveForm').removeAttribute("disabled");
  } else {
    console.log('nope not yet');
    document.getElementById('saveForm').setAttribute("disabled", null);
  }
});

Content Security Policy: The page’s settings blocked the loading of a resource

I have implemented Google Sign-In button in a ReactJS web client.
After successful sign-in the page fails to get redirected from “https://accounts.google.com/…”
back to my web-client URL which is http://localhost:5000.

This is from browser console logs:

Navigated to http://localhost:3000/login
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
POSThttp://localhost:3000/login
[HTTP/1.1 404 Not Found 17ms]

Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:3000/favicon.ico (“default-src”).

This is the code for GoogleAuth button which I copied from here

import { useEffect, useRef } from 'react'

const loadScript = (src) =>
    new Promise((resolve, reject) => {
        if (document.querySelector(`script[src="${src}"]`)) return resolve()
        const script = document.createElement('script')
        script.src = src
        script.onload = () => resolve()
        script.onerror = (err) => reject(err)
        document.body.appendChild(script)
    })

const GoogleAuth = () => {
    // Refer Google Identity API documentation from https://developers.google.com/identity/gsi/web/reference/js-reference#ux_mode

    const googleButton = useRef(null);

    useEffect(() => {
        const src = 'https://accounts.google.com/gsi/client'
        const id = "<I gave valid ClientID>"

        // Load Google sign-in page by redirecting the page.
        loadScript(src)
            .then(() => {
                /*global google*/
                console.log(google)
                google.accounts.id.initialize({
                    client_id: id,
                    ux_mode: "redirect",
                    login_uri: window.location,
                    callback: handleCredentialResponse,
                })
                google.accounts.id.renderButton(
                    googleButton.current,
                    { theme: 'outline', size: 'large' }
                )
            })
            .catch(console.error)

        return () => {
            const scriptTag = document.querySelector(`script[src="${src}"]`)
            if (scriptTag) document.body.removeChild(scriptTag)
        }
    }, [])

    function handleCredentialResponse(response) {
        console.log("Encoded JWT ID token: " + response.credential);
    }

    return (
        <div ref={googleButton}></div>
    )
}

export default GoogleAuth

I dont see the the console logs of callback “handleCredentialResponse”.

What am I missing?
How can I fix this issue without disabling browser safety features?

Bookmarklet – Replacing unique parts of current URL domain-wide then redirecting

I’m trying to create a bookmarklet that redirects me from a product page to the file (mp3 in this case) related to that product.

I currently have a functional bookmarklet I was testing, but it only works on the current product page and I’m trying to modify it to work on all pages in that domain.

Ex:
I’m trying to redirect this (current page):

https://www.samplewebsite.com/product-title/12345.item

to here (website’s sample file I’m trying to download for reference in my own library of products I own from this site)

https://string.samplehost.audio/12345.mp3

Here’s what I have right now just to test the basics

javascript:(function() {window.location=window.location.toString().replace('https://www.samplewebsite.com/product-page/','https://string.samplehost.audio/').replace('.item','.mp3');})()

This is working, but only for current product page, which isn’t helpful when I’m trying to make the bookmark work on the entire domain regardless of what product I’m looking at. I’m trying to figure out a way to always remove the bolded portion in this example which is unique to each product https://www.samplewebsite.com/**product-title**/

I know this shouldn’t be too difficult since the product number on the URL and the name of the mp3 on the host site are always the same. I don’t know if it would be best to replace everything except the number of the product, then add the correct redirect URL before it and .mp3 after, or if there’s some easier way to do this.

Or is there a way to replace everything before the last forward slash of the url instead? Then I could use a simple replace function to replace “.item” with “.mp3”

Why aren’t instance properties available in `getOwnPropertyNames`? [duplicate]

Consider this sample class:

class Test {
    static staticProperty = `static property`;
    static staticMethodArrow = () => console.log(`static method arrow`);
    static staticMethodTraditional() {
        console.log(`static method traditional`);
    }
    
    instanceProperty = `instance property`;
    instanceMethodArrow = () => console.log(`instance method arrow`);
    instanceMethodTraditional() {
        console.log(`instance method traditional`);
    }
}

If we run Object.getOwnPropertyNames(Test) it returns all the static methods and properties as expected:

['length', 'name', 'prototype', 'staticMethodTraditional', 'staticProperty', 'staticMethodArrow']

If we run Object.getOwnPropertyNames(Test.prototype) I would expect the result to be:

['constructor', 'instanceMethodTraditional', 'instanceProperty', 'instanceMethodArrow']

However, it is actually just this:

['constructor', 'instanceMethodTraditional']

Why doesn’t Test.prototype have all the instance methods and properties we’ve defined, and how can we get their names (ideally without having to instantiate a new Test())?

I’m not able to add image uploads to my existing form | NextJS

I want to save the images locally and save the path in the database. I’ve tried several methods but it always ends up giving me an error somewhere. I’ve never worked with uploading images so I’m having a lot of difficulty. Mainly because I was sending the form data in Json, but I can’t send images like that.

I tried to make a formData but I couldn’t adapt the api for that. I tried to convert to base64 to be able to send it via json and then deal with the image in the api but it also failed. I’m quite a beginner, can anyone help me?

I have the code on github if you want to check it out
Github: https://github.com/goncalojbsousa/onlinecloset_imgupld

Puppeteer – Can’t set cookies? (“is missing the following properties from type ‘CookieParam’: name, value”)

my cookie variable:

const cookies = [{
    domain: ".apollo.io",
    expirationDate: 1703861523,
    hostOnly: false,
    httpOnly: false,
    name: "__hssc",
    path: "/",
    sameSite: "lax",
    secure: false,
    session: false,
    storeId: "0",
    value: "21978340.1.170385",
    id: 1,
  },

me calling setCookie from puppeteer:

await page.setCookie(cookies);

the error message that it gives me:

error TS2345: Argument of type '{ domain: string; expirationDate: number; hostOnly: boolean; httpOnly: boolean; name: string; path: string; sameSite: string; secure: boolean; session: boolean; storeId: string; value: string; id: number; }[]' is not assignable to parameter of type 'CookieParam'.
  Type '{ domain: string; expirationDate: number; hostOnly: boolean; httpOnly: boolean; name: string; path: string; sameSite: string; secure: boolean; session: boolean; storeId: string; value: string; id: number; }[]' is missing the following properties from type 'CookieParam': name, value

As you can see, name and value are not missing… I went one-by-one and nothing seems to differ in both…

I’ve tried changing types, googling “CookieParams” type, and putting quotes on the cookie keys, etc for quite some time

Still can’t figure it out. What’s the problem that I’m not seeing here?

Full code:

import puppeteer from 'puppeteer-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';

const defaultPuppeteerOptions = {headless:false};
const ApolloUrl = 'https://apollo.io';
const cookies = [{
    domain: ".apollo.io",
    expirationDate: 1703861523,
    hostOnly: false,
    httpOnly: false,
    name: "__hssc",
    path: "/",
    sameSite: "lax",
    secure: false,
    session: false,
    storeId: "0",
    value: "21978340.1.1703859723",
    id: 1,
  },

]

export default async function Start() {
    const browser = await puppeteer.launch(defaultPuppeteerOptions);
    const page = await browser.newPage();
    await page.goto(ApolloUrl);
    await page.setCookie(cookies);
}

Submit button needs to be clicked twice to log out the query response

I got a problem with a login system I’m building with React, PHP and MySQL. The code itself seems to be working fine, the “div” which contains the data of the user requested by the query displays the result correctly, but the “Login” button displays no user at the first click, then displays the correct result at the second click. I checked the post function of the JS part but everything should work at the first time.
Here is the code:

LoginIndex.jsx:

import React from "react";
import {useState} from 'react';
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap/dist/js/bootstrap.js";
import "../Style.css";
import axios from 'axios';

function LoginIndex(){

    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [data, setData] = useState('');

    const handleSubmit = () => { 
        const url = "http://localhost/login.php";

        let loginFormData = new FormData();

        loginFormData.append('username', username);
        loginFormData.append('password', password);

        axios.post(url, loginFormData)
        .then((response) => {setData(response.data); document.getElementById('prova').innerHTML = data})
        .catch(error => alert(error));
    }

    const signupRedirect = () => {
        window.location.replace('/signup');
    }

    window.top.document.title = "SyncHub \ Accedi";

    return (
        <>
            <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"rel="stylesheet"/>
            <div class="container" id="loginbody">
                <div id="prova"></div>
                <form id="loginform">
                    <h2 class="text-center mb-4">Login</h2>
                    <div class="form-group">
                        <label for="username">Username</label>
                        <input type="text" class="form-control" id="username" value={username} onChange={(e) => setUsername(e.target.value)} placeholder="Inserisci username" name="username"></input>
                    </div>
                    <div class="form-group">
                        <label for="password">Password</label>
                        <input type="password" class="form-control" id="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Inserisci la password" name="password"></input>
                    </div>
                    <button type="button" class="btn btn-primary btn-block" name="submit" onClick={handleSubmit}>Login</button>
                    <button type="button" class="btn btn-primary btn-block" onClick={signupRedirect}>Crea un account</button>
                </form>
            </div>

            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
        </>
    );
}

export default LoginIndex;

login.php:

<?php
header('Access-Control-Allow-Origin: *');

/* require 'entities.php'; */
require 'functions.php';

includeEnv();

$c = newConnection();

$username = $_POST['username'];
$password = $_POST['password'];

fetchUserFromPost($username, $password);
?>

fetchUserFromPost():

function fetchUserFromPost(
    $username, 
    $password){
    $builder = $GLOBALS['c']->createQueryBuilder();
    $query = $builder->select('*')->from('utenti')->where('username="' . $username . '" and password="' . $password . '"');
    $result = $GLOBALS['c']->fetchAllAssociative($query);
    print_r($result);
}

The query actually returns the result, but only if the button is clicked twice.

React useState not behaving as expected

I’m trying to create a description box that can be edited in “edit mode”, but just diplays the static definition otherwise.

During edit mode, I want the state to be recorded in the react state “editedHTMLDefinition”, before being recorded to the global state when exiting “edit mode”.

const EditableDescription = ({
  htmlDefinition,
  setHTMLDefinition = () => {},
  editMode,
  word,
}) => {
  const [editorState, setEditorState] = useState();
  const [editedHTMLDefinition, setEditedHTMLDefinition] = useState(null);
  const editedHTMLRef = useRef(null);
  // const editorStateRef = useRef(null);

  const onChange = (newEditorState, editor) => {
    setEditorState(newEditorState);
    editor.current = newEditorState;
  };

  const CustomContent = (
    <ContentEditable
      style={{
        position: "relative",
        borderColor: "rgba(255,211,2,0.68)",
        border: "1px solid gray",
        borderRadius: "5px",
        maxWidth: "100%",
        padding: "10px",
      }}
      value={editorState} // Use value prop to set the content
      onChange={onChange} // Handle content changes
    />
  );

  function LoadContentPlugin() {
    const [editor] = useLexicalComposerContext();
    editor.update(() => {
      const parser = new DOMParser();
      const dom = parser.parseFromString(htmlDefinition, "text/html");

      // Once you have the DOM instance it's easy to generate LexicalNodes.
      const nodes = $generateNodesFromDOM(editor, dom);
      // Select the root
      const root = $getRoot();
      const paragraphNode = $createParagraphNode();

      nodes.forEach((n) => paragraphNode.append(n));

      root.append(paragraphNode);
    });
  }

  const lexicalConfig = {
    namespace: word,
    onError: (e) => {
      console.log("ERROR:", e);
    },
  };

  const editableDescription = (
    <div style={{ padding: "20px" }}>
      <LexicalComposer initialConfig={lexicalConfig}>
        <RichTextPlugin
          contentEditable={CustomContent}
          ErrorBoundary={LexicalErrorBoundary}
        />
        <OnChangePlugin
          onChange={(editorState, editor) => {
            editor.update(() => {
              setEditedHTMLDefinition((prevEditedHTMLDefinition) => {
                const newEditedHTMLDefinition = String(
                  $generateHtmlFromNodes(editor, null)
                );
                console.log(
                  "EDITOR STATE: ",
                  JSON.stringify(editorState),
                  "nHTML: ",
                  $generateHtmlFromNodes(editor, null),
                  "nEdited HTML: ",
                  newEditedHTMLDefinition,
                  "nprevEditedHTMLDefinition",
                  prevEditedHTMLDefinition
                );
                return newEditedHTMLDefinition;
              });
              editedHTMLRef.current = $generateHtmlFromNodes(editor, null);
            });
          }}
        />
        <HistoryPlugin />
        <LoadContentPlugin />
      </LexicalComposer>
    </div>
  );

  const [descriptionBox, setDescriptionBox] = useState(
    <StaticDescription htmlDefinition={htmlDefinition} />
  );

  useEffect(() => {
    console.log("editedHTMLDefinition changed: ", editedHTMLDefinition);
  }, [editedHTMLDefinition]);

  useEffect(() => {
    console.log("Edit mode changed for ", htmlDefinition);
    if (!editMode) {
      // handle save
      console.log("internal edited desc: ", editedHTMLDefinition);
      console.log("ref state: ", editedHTMLRef);
      setHTMLDefinition(editedHTMLDefinition);
      setDescriptionBox(<StaticDescription htmlDefinition={htmlDefinition} />);
    } else {
      // switch to edit mode
      setDescriptionBox(editableDescription);
    }
  }, [editMode]);

  return descriptionBox;
};

The issue is, the state is not being recorded as expected. In the first “useEffect” call, as I’m editing, I’m getting the correct values from the state based on what I’ve written in the box.

However, when I change the editMode, the editedHTMLDefinition gives me “null” as the value (same as its initial state). I tried using a ref instead but I got the same result.

I feel like it might be because editMode is a react state thats being passed in, so maybe the component is rerendering when it changes, so the editedHTMLDefinition also resets. How do I solve this? I want the component to react to when editMode changes

editMode is a higher level state controlled by a single button that’s being passed to multiple editableDescriptions at once

Table Footer not fixed in the bottom of every page in ios devices

Table Footer not fixed in the bottom of every page in ios devices. it works fine in android and windows devices
The code is:

  const downloadPdfRef = useRef();
  let date = new Date();
  const handlePrint = useReactToPrint({
    content: () => downloadPdfRef.current,
    documentTitle: `JustATutor-${date.getDate()}-${date.getMonth()}-${date.getFullYear()}`,
    removeAfterPrint: false,
  }); 
 
  const manipulateDOM = () => {
    let ql_container_node = document.querySelectorAll(".ql-container");
    let ql_editor = document.querySelectorAll(".ql-editor");
    ql_container_node?.forEach((element) => element.classList.add("hide-border"));
    ql_editor?.forEach((element) => element.classList.add("reduce_editor_padding"));
  };
  const quillRef = useCallback((node) => {
    if (node !== null) {
      manipulateDOM();
    }
  }, []);
  useEffect(() => {
    manipulateDOM();
  }, [format]);

  return (
    <>
      <Container
        maxWidth={false}
        sx={{
          paddingRight: { xs: "16px" },
          paddingLeft: { xs: `${globalVariable}px`, md: `${globalVariablemd}px` },
          paddingTop: "10px",
          paddingBottom: "16px",
        }}
      >
        <>
          <div className="flex flex-col w-full min-h-full print_questions_container " >
            <div className="view-question-container p-8 pb-8 bg-[#ffffff] relative w-full" ref={downloadPdfRef} style={{minHeight: '100vh'}}>
              <div>
                <div className="flex justify-between w-full">
                  <div className="self-end">
                    <Typography variant="h6" className="print-heading-primary uppercase font-bold w-fit leading-none font-arial my-1">
                      JustATutor
                    </Typography>
                    <Typography className="print-heading-secondary font-bold leading-none font-arial">{headerText}</Typography>
                  </div>
                  <img src={HeaderImage} alt="Character Image" className="h-auto w-[60px] -mb-1" />
                </div>
                <Divider
                  className="h-1"
                  sx={{
                    marginBottom: "12px",
                  }}
                />
                <Typography className="print-heading-secondary text-2xl leading-none font-romans" sx={{ lineHeight: "1" }}>
                  <pre style={{ fontFamily: "inherit" }}>{topicText}</pre>
                </Typography>
                <Divider
                  className="h-1"
                  sx={{
                    marginTop: "12px",
                    marginBottom: "12px",
                  }}
                />
              </div>

              <Table>
                <TableBody className="page-breaker">
                  <TableRow style={{ borderBottom: "none" }}>
                    <TableCell sx={{ borderBottom: "none" }}>
                      <div className="mt-1 mb-1">
                        <div>
                          <Typography
                            variant="h6"
                            className="font-bold font-romans leading-[0.6] w-fit border-black text-black "
                            sx={{ fontSize: "16px", borderBottomWidth: "1px", lineHeight: "0.8", marginBottom: "0.5rem" }}
                          >{`Question 1`}</Typography>
                        </div>
                        <div>
                          <Typography
                            variant="h6"
                            className="font-bold font-romans leading-[0.6] mt-3 w-fit border-black text-black"
                            sx={{ fontSize: "16px", borderBottomWidth: "1px", lineHeight: "0.8", marginBottom: "0.5rem" }}
                          >
                            Answer
                          </Typography>
                        </div>
                      </div>
                    </TableCell>
                  </TableRow>
                </TableBody>
                <TableFooter>
                  <TableRow>
                    <TableCell>
                      <div className="flex justify-between footer-image mt-4" ref={quillRef}>
                        <Typography className="font-bold leading-none font-arial" sx={{ fontSize: "12px" }}>
                          {headerText}
                        </Typography>
                        <img className="footer-logo " src={FooterLogopng} alt="logo" />
                      </div>
                    </TableCell>
                  </TableRow>
                </TableFooter>
              </Table>
            </div>
            <Divider className="h-2 my-10" />
          </div>

          <div className="text-end ">
            <Button
              text={"Download as PDF"}
              primary
              className="px-8 my-4 py-2"
              onClick={() => {
                handlePrint();
              }}
            />
          </div>
        </>
      </Container>
    </>
  );
};

export default PrintPdfPage;

And its CSS IS:


@media print {
  /* html and body tweaks */
  html, body {
    height: auto !important;
    overflow: initial !important;
    background: none;
    font-size: 7.5pt; /* changing to 10pt has no impact */
  }
.topNavBar, .HideOnPrint{
  display: none;
}
  /* Page breaks */
  .page-break-after {
    display: block;
    page-break-after: always;
    position: relative;
  }

  tbody tr td {
    margin-top: -8px;
    padding-top: 80px;
    page-break-inside: avoid;
  }

  .print_questions_container .ql-container, td {
    border-bottom: none !important;
    padding: 0px 0px !important;
  }

  .section-answers table {
    page-break-before: always !important;
    page-break-inside: avoid;
  }
 
  .page-breaker {
    page-break-after: auto;
    /* page-break-after: always; */
  }

  .page-breaker tr {
    padding-top: 2px;
  }

  /*---Below styles are to avoid page break in questions in Question and then Answers mode.*/
  .page-breaker tr {
    display: block !important;
    page-break-inside: avoid !important;
  }
  .page-breaker tr td {
    display: block !important;
    page-break-inside: avoid !important;
  }
  /* ------- */

  body .footer-image {
    position: absolute;
    bottom: 5px;
    left: 0;
    padding: 0 1rem;
    width: 100% !important;
  }
  
  body .footer-placeholder {
    display: block;
  }

  .page-break-before {
    display: block;
    page-break-before: always;
    position: relative;
  }

  @page {
    size: A4; /* DIN A4 standard, Europe */
    margin: 20px 35px 0.8rem 35px;
    overflow: hidden;
  } 
}

output in windows devices is:
Output in Windows Laptop
output in ios devices is
Output in Ios Device

I want that the footer in stick in the bottom of every page while printing

TypeError: Invalid attempt to destructure non-iterable instance with useContext in React

LOG [TypeError: Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a Symbol.iterator method.]

with my UserContext :

import React, { useContext, useEffect, useLayoutEffect, useState } from "react";
import { useNavigation } from "@react-navigation/native";
import { Ionicons } from '@expo/vector-icons';
import { UserType } from "../UserContext";

const [userId, setUserId] = useContext(UserType);

const token = await AsyncStorage.getItem("authToken");
            const decodedToken = jwt_decode(token);
            const userId = decodedToken.userId;
            console.log(userId);
            setUserId(userId);

this is my UserContext.js

import { createContext, useState } from 'react';

const UserType = createContext();

const UserContext = ({ children }) => {
    const { userId, setUserId } = useState("");
    return (
        <UserType.Provider value={{ userId, setUserId }}>
            {children}
        </UserType.Provider>
    )
}

export {UserType, UserContext}

My App.js

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import StackNavigator from './StackNavigator'
import { UserContext } from './UserContext';
export default function App() {
  return (
    <>
    <UserContext>
    <StackNavigator/>
    </UserContext>
    </>
  );
}

please if someone can help me

i have tried to change

const [userId, setUserId] = useContext(UserType);

with

const {userId, setUserId} = useContext(UserType);

but it give me this error

TypeError: setUserId is not a function (it is undefined)

Electron App Shows Blank Screen After Packaging, but Works Locally

Problem Description:

I’m encountering an issue with my Electron app. After packaging the app, it displays a blank screen. However, when running it locally with npm run electron:serve, everything works fine.

Code Details:

  • main.js:

    const { app, BrowserWindow } = require('electron')
    
    const path = require('path')
    const isDev = require('electron-is-dev')
    
    require('@electron/remote/main').initialize()
    
    function createWindow() {
      // Create the browser window.
      const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true, // false tried both
          enableRemoteModule: true
        }
      })
    
      win.loadURL(
        isDev
          ? 'http://localhost:3000'
          : `file:///Users/avinashkumaranshu/Project/Desktop/react-electron/build/index.html`
      )
    }
    
    app.on('ready', createWindow)
    
    // Quit when all windows are closed.
    app.on('window-all-closed', function () {
      // On OS X it is common for applications and their menu bar
      // to stay active until the user quits explicitly with Cmd + Q
      if (process.platform !== 'darwin') {
        app.quit()
      }
    })
    
    app.on('activate', function () {
      // On OS X it's common to re-create a window in the app when the
      // dock icon is clicked and there are no other windows open.
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })

  • App.js:

   import { useState, useMemo } from 'react'
   import { FilesViewer } from './FilesViewer'
   
   const fs = window.require('fs')
   const pathModule = window.require('path')
   
   const { app } = window.require('@electron/remote')
   
   const formatSize = size => {
     var i = Math.floor(Math.log(size) / Math.log(1024))
     return (
       (size / Math.pow(1024, i)).toFixed(2) * 1 +
       ' ' +
       ['B', 'kB', 'MB', 'GB', 'TB'][i]
     )
   }
   
   function App() {
     const [path, setPath] = useState(app.getAppPath())
   
     const files = useMemo(
       () =>
         fs
           .readdirSync(path)
           .map(file => {
             const stats = fs.statSync(pathModule.join(path, file))
             return {
               name: file,
               size: stats.isFile() ? formatSize(stats.size ?? 0) : null,
               directory: stats.isDirectory()
             }
           })
           .sort((a, b) => {
             if (a.directory === b.directory) {
               return a.name.localeCompare(b.name)
             }
             return a.directory ? -1 : 1
           }),
       [path]
     )
   
     const onBack = () => setPath(pathModule.dirname(path))
     const onOpen = folder => setPath(pathModule.join(path, folder))
   
     const [searchString, setSearchString] = useState('')
     const filteredFiles = files.filter(s => s.name.startsWith(searchString))
   
     return (
       <div className="container mt-2">
         <h4>{path}</h4>
         <div className="form-group mt-4 mb-2">
           <input
             value={searchString}
             onChange={event => setSearchString(event.target.value)}
             className="form-control form-control-sm"
             placeholder="File search"
           />
         </div>
         <FilesViewer files={filteredFiles} onBack={onBack} onOpen={onOpen} />
       </div>
     )
   }
   
   export default App

  • package.json:

   {
     "name": "electron-react",
     "version": "0.1.0",
     "private": true,
     "dependencies": {
       "@electron/remote": "^1.0.2",
       "@testing-library/jest-dom": "^5.11.4",
       "@testing-library/react": "^11.1.0",
       "@testing-library/user-event": "^12.1.10",
       "bootstrap": "^5.0.0-beta1",
       "electron-is-dev": "^1.2.0",
       "react": "^17.0.1",
       "react-dom": "^17.0.1",
       "react-scripts": "4.0.1",
       "web-vitals": "^0.2.4"
     },
     "main": "public/main.js",
     "homepage": "./",
     "scripts": {
       "start": "react-scripts start",
       "build": "react-scripts build",
       "test": "react-scripts test",
       "eject": "react-scripts eject",
       "electron:serve": "concurrently -k "cross-env BROWSER=none yarn start" "yarn electron:start"",
       "electron:build": "yarn build && electron-builder -c.extraMetadata.main=build/main.js",
       "electron:start": "wait-on tcp:3000 && electron ."
     },
     "build": {
       "extends": null,
       "appId": "com.example.electron-cra",
       "files": [
         "dist/**/*",
         "build/**/*",
         "node_modules/**/*",
         "package.json"
       ],
       "directories": {
         "buildResources": "assets"
       }
     },
     "eslintConfig": {
       "extends": [
         "react-app",
         "react-app/jest"
       ]
     },
     "browserslist": {
       "production": [
         ">0.2%",
         "not dead",
         "not op_mini all"
       ],
       "development": [
         "last 1 chrome version",
         "last 1 firefox version",
         "last 1 safari version"
       ]
     },
     "devDependencies": {
       "concurrently": "^5.3.0",
       "cross-env": "^7.0.3",
       "electron": "^16.0.0",
       "electron-builder": "^24.9.1",
       "prettier": "^2.2.1",
       "wait-on": "^5.2.1"
     }
   }

Additional Information:

  • Dependencies:
    • electron: 16.0.0
    • electron-builder: 24.9.1
  • Scripts:
    • How you run the app locally (npm run electron:serve).
    • How you build and package the app (npm run electron:build).
  • Steps Taken:
    • I’ve checked the console for errors but didn’t find anything unusual.
    • I’ve hardcoded the paths in the main.js file.

Environment:

  • Operating System: macOS
  • Node.js: 14.21.3