ReactDOM.createPortal() renders empty element when called in a function

I have a simple React.js app that tries to render content in a Portal on a callback, does someone have any ideas why it isn’t rendering anything?

Runnable CodeSandbox

import React from 'react'
import ReactDOM from 'react-dom'
import './App.css';

function App() {
  const showElement = React.useCallback(() => {
    const element = document.createElement('div');
    document.querySelector('body').appendChild(element)
    ReactDOM.createPortal(() => <div>TEST</div>, element)
  }, [])
  
  return (
    <div className="App">
      <button onClick={showElement}>Click to Render Portal</button>
    </div>
  );
}

export default App;

three java scripts, one overwriting one

I have two “nav” bars. The top nav scrolls in slow from the top-like its been trigged by the hiding navscript. The bottom nav acts as it should, displays on page open and disappears when page scrolls up then reappears when page scrolls down. Most time the page loads correctly and displays the random image background with the nav bar at top but the top nav always slides in after page laod. I had to put a bookmark to make the page load and show the random image background, #top. Otherwise the page would load at the h1 marker and hide the random image background which is in a fixed position. After numerous nav clicking back and forth the page loads to the top of the container and hides the random image background. Every time the page loads I can briefly see the h1 where the nav bar should be, its bright orange so I see it flash.

 <h2 id="top"></h2>
 <nav id="navbar">
    <ul>
        <li><b><a href="indexWEATHER.html">Weather</a></b></li>
        <li><b><a href="indexRace.html">Race</a></b></li>
        <li><b><a href="index.html"><img src="img/Burgee_WSC.png" width="30" height="10"></a> 
 </b></li>
        <li><b><a href="indexTour.html">Tour</a></b></li>
        <li><b><a href="indexMembers.html#top" class='active-page'>Club</a></b></li>
    </ul>

 </nav>

<nav id="secondLineNav">
    <ul>
        <li><b><a href="*.html">Sign Up</a></b></li>
        <li><b><a href="*.html">Zoom</a></b></li>
        <li><b><a href="*.html">Current Windword</a></b></li>
        <li><b><a href="*.html">Archives</a></b></li>
        <li><b><a href="indexPhotos.html">Photos</a></b></li>
        <li><b><a href="*.html">Winwords</a></b></li>
    </ul>
  </nav>

   <div class="container">

<h1>Updates, calendar and site map</h1>
   </div>


  <script >
    var random_images_array = ["1.jpg", "2.jpg","3.jpg","4.jpg","5.jpg"];
    
    function getRandomImage(imgAr, path) {
        path = path || 'random/'; // default path here
        var num = Math.floor( Math.random() * imgAr.length );
        var img = imgAr[ num ];
        var imgStr = '<img src="' + path + img + '" alt = "Random Image of Club">';
        document.write(imgStr); document.close();
    }
    </script>

   <div class="background">
          
    <div class="randomimages">
        <!--<img src="" alt="">-->
            <script type="text/javascript">getRandomImage(random_images_array);</script>
    </div>
    </div><!--background-->
    </script>

    <script type="text/javascript">  
    var lastScrollTop = 0;
    navbar = document.getElementById("navbar");
    window.addEventListener("scroll", function(){
    var scrollTop = window.pageYOffest || document  
        .documentElement.scrollTop;
    if(scrollTop > lastScrollTop){
        navbar.style.top="-90px";
    } else {
        navbar.style.top="0";
    }
    lastScrollTop = scrollTop;
    })
    </script>

    <script type="text/javascript">  
    var lastScrollTopb = 81;
    secondLineNav = document.getElementById("secondLineNav");
    window.addEventListener("scroll", function(){
    var scrollTopb = window.pageYOffest || document  
        .documentElement.scrollTop;
    if(scrollTopb > lastScrollTopb){
      secondLineNav.style.top="-90px";
    } else {
      secondLineNav.style.top="81px";
    }
    lastScrollTopb = scrollTopb;
   })
   </script>

    nav{
      width: 100%;
      height: 80px;
      background-color: rgba(0, 0, 0, 0.5);
      line-height: 80px;
      z-index: 999;
      position: fixed;
      transition: .5s;    
      white-space:nowrap;

     }

    nav ul{
   text-align: center;
    font-size: 20px;
    }

   nav ul li{
    list-style: none;
    display: inline-block;  /*take this out for vertical list*/
   /*transition: 0.8S all;*/
   vertical-align: top;
   justify-content: space-between;


   /*border-left: 1px solid #fff;
   border-right: 1px solid #ccc;
   width: 16.6667%; /* fallback for non-calc() browsers 
   width: calc(100% / 6);*/
   box-sizing: border-box;
   }


  nav ul li:hover{
 /*background-color: #f39c1a4b;*/
  border-radius: 10px;
  transform: scale(1.2,1.2);


  }

 nav ul li a{
 text-decoration: none;
 font-family: 'Lexend Mega', sans-serif;
 font-size: 100%;
 letter-spacing: .2rem;
 color: #dddcdc;
 padding: 30px;
 text-align: center;
 text-transform: uppercase;
  }
 nav .active-page{

 background-color: rgba(191, 191, 191, 0.336);
 }


   .background{
    background:rgb(91 111 155 / 48%);
    height: 90vh;
    z-index: auto;
    width: auto;
  }

  .randomimages img{
  
  position: fixed;
  top:400px;
  right: 50%;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
  z-index: -1;
  transform: translateX(-50%) translateY(-50%);
  }

How to stop setInterval with javasript?

I want to start from 0. Until it reaches the numbers 709 and 54, Stop it.

HTML

<span class="card-title h5 counter"> 709 + </span>
<span class="card-title h5 counter"> 54+ </span>

script.js

let intervals = [];
let counter  = [];
let elements = document.getElementsByClassName('counter');
Array.from(elements).forEach((element, index) => {
    counter[index] = 0;
    intervals[index] = setInterval(()=> {
            counter[index]++;
            element.innerText=counter;
        }
        , 50);
})

But this code goes on indefinitely and does not end.

SVG background image (in CSS with URL link) renders in local host, but doesn’t render in production (heroku)

@import url("https://fonts.googleapis.com/css2?family=Arvo:wght@400;700&family=Comfortaa:wght@300;400;500;600;700&family=IBM+Plex+Serif:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700&display=swap");

body {
  margin: 0;
  font-family: "Arvo", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto",
    "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

html {
  background-image: url("data:image/svg+xml,<svg id='patternId' width='100%' height='100%' xmlns='http://www.w3.org/2000/svg'><defs><pattern id='a' patternUnits='userSpaceOnUse' width='35.584' height='30.585' patternTransform='scale(2) rotate(0)'><rect x='0' y='0' width='100%' height='100%' fill='hsla(0,0%,100%,1)'/><path d='M36.908 9.243c-5.014 0-7.266 3.575-7.266 7.117 0 3.376 2.45 5.726 5.959 5.726 1.307 0 2.45-.463 3.244-1.307.744-.811 1.125-1.903 1.042-3.095-.066-.811-.546-1.655-1.274-2.185-.596-.447-1.639-.894-3.162-.546-.48.1-.778.58-.662 1.06.1.48.58.777 1.06.661.695-.149 1.274-.066 1.705.249.364.265.546.645.562.893.05.679-.165 1.308-.579 1.755-.446.48-1.125.744-1.936.744-2.55 0-4.188-1.538-4.188-3.938 0-2.466 1.44-5.347 5.495-5.347 2.897 0 6.008 1.888 6.388 6.058.166 1.804.067 5.147-2.598 7.034a.868.868 0 00-.142.122c-1.311.783-2.87 1.301-4.972 1.301-4.088 0-6.123-1.952-8.275-4.021-2.317-2.218-4.7-4.518-9.517-4.518-4.094 0-6.439 1.676-8.479 3.545.227-1.102.289-2.307.17-3.596-.496-5.263-4.567-7.662-8.159-7.662-5.015 0-7.265 3.574-7.265 7.116 0 3.377 2.45 5.727 5.958 5.727 1.307 0 2.449-.463 3.243-1.308.745-.81 1.126-1.903 1.043-3.095-.066-.81-.546-1.654-1.274-2.184-.596-.447-1.639-.894-3.161-.546-.48.1-.778.58-.662 1.06.099.48.579.777 1.059.66.695-.148 1.275-.065 1.705.25.364.264.546.645.563.893.05.679-.166 1.307-.58 1.754-.447.48-1.125.745-1.936.745-2.549 0-4.188-1.539-4.188-3.939 0-2.466 1.44-5.345 5.495-5.345 2.897 0 6.008 1.87 6.389 6.057.163 1.781.064 5.06-2.504 6.96-1.36.864-2.978 1.447-5.209 1.447-4.088 0-6.124-1.952-8.275-4.021-2.317-2.218-4.7-4.518-9.516-4.518v1.787c4.088 0 6.123 1.953 8.275 4.022 2.317 2.218 4.7 4.518 9.516 4.518 4.8 0 7.2-2.3 9.517-4.518 2.151-2.069 4.187-4.022 8.275-4.022s6.124 1.953 8.275 4.022c2.318 2.218 4.701 4.518 9.517 4.518 4.8 0 7.2-2.3 9.516-4.518 2.152-2.069 4.188-4.022 8.276-4.022s6.123 1.953 8.275 4.022c2.317 2.218 4.7 4.518 9.517 4.518v-1.788c-4.088 0-6.124-1.952-8.275-4.021-2.318-2.218-4.701-4.518-9.517-4.518-4.103 0-6.45 1.683-8.492 3.556.237-1.118.304-2.343.184-3.656-.497-5.263-4.568-7.663-8.16-7.663z'  stroke-width='1' stroke='none' fill='hsla(34, 100%, 95%, 1)'/><path d='M23.42 41.086a.896.896 0 01-.729-.38.883.883 0 01.215-1.242c2.665-1.887 2.764-5.23 2.599-7.034-.38-4.187-3.492-6.058-6.389-6.058-4.055 0-5.495 2.88-5.495 5.346 0 2.4 1.639 3.94 4.188 3.94.81 0 1.49-.265 1.936-.745.414-.447.63-1.076.58-1.755-.017-.248-.2-.629-.547-.893-.43-.315-1.026-.398-1.704-.249a.868.868 0 01-1.06-.662.868.868 0 01.662-1.059c1.523-.348 2.566.1 3.161.546.729.53 1.209 1.374 1.275 2.185.083 1.191-.298 2.284-1.043 3.095-.794.844-1.936 1.307-3.244 1.307-3.508 0-5.958-2.35-5.958-5.726 0-3.542 2.25-7.117 7.266-7.117 3.591 0 7.663 2.4 8.16 7.663.347 3.79-.828 6.868-3.344 8.656a.824.824 0 01-.53.182zm0-30.585a.896.896 0 01-.729-.38.883.883 0 01.215-1.242c2.665-1.887 2.764-5.23 2.599-7.034-.381-4.187-3.493-6.058-6.389-6.058-4.055 0-5.495 2.88-5.495 5.346 0 2.4 1.639 3.94 4.188 3.94.81 0 1.49-.266 1.936-.746.414-.446.629-1.075.58-1.754-.017-.248-.2-.629-.547-.894-.43-.314-1.026-.397-1.705-.248A.868.868 0 0117.014.77a.868.868 0 01.662-1.06c1.523-.347 2.566.1 3.161.547.729.53 1.209 1.374 1.275 2.185.083 1.191-.298 2.284-1.043 3.095-.794.844-1.936 1.307-3.244 1.307-3.508 0-5.958-2.35-5.958-5.726 0-3.542 2.25-7.117 7.266-7.117 3.591 0 7.663 2.4 8.16 7.663.347 3.79-.828 6.868-3.344 8.656a.824.824 0 01-.53.182zm29.956 1.572c-4.8 0-7.2-2.3-9.517-4.518-2.151-2.069-4.187-4.022-8.275-4.022S29.46 5.486 27.31 7.555c-2.317 2.218-4.7 4.518-9.517 4.518-4.8 0-7.2-2.3-9.516-4.518C6.124 5.486 4.088 3.533 0 3.533s-6.124 1.953-8.275 4.022c-2.317 2.218-4.7 4.518-9.517 4.518-4.8 0-7.2-2.3-9.516-4.518-2.152-2.069-4.188-4.022-8.276-4.022V1.746c4.8 0 7.2 2.3 9.517 4.518 2.152 2.069 4.187 4.022 8.275 4.022s6.124-1.953 8.276-4.022C-7.2 4.046-4.816 1.746 0 1.746c4.8 0 7.2 2.3 9.517 4.518 2.151 2.069 4.187 4.022 8.275 4.022s6.124-1.953 8.275-4.022c2.318-2.218 4.7-4.518 9.517-4.518 4.8 0 7.2 2.3 9.517 4.518 2.151 2.069 4.187 4.022 8.275 4.022s6.124-1.953 8.275-4.022c2.317-2.218 4.7-4.518 9.517-4.518v1.787c-4.088 0-6.124 1.953-8.275 4.022-2.317 2.234-4.717 4.518-9.517 4.518z'  stroke-width='1' stroke='none' fill='hsla(34, 100%, 95%, 1)'/></pattern></defs><rect width='800%' height='800%' transform='translate(0,0)' fill='url(%23a)'/></svg>");
  background-position: center;
  min-height: 100%;
  background-repeat: no-repeat;
}

* {
  font-family: "IBM Plex Serif" !important;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
}

This is my index.css file. The SVG was generated using pattern.monster (wave 7, with colours WHITE #fff5e8 #fff5e8)

The background isn’t stored locally, but is fetched from the URL. The background shows in localhost, but not in production on heroku.

Anyone have any idea on whats happening?

How do you push data to firebase when a javascript button is clicked?

I am a complete noob when it comes to JavaScript and cannot seem to solve this problem.

I have a main.js file that was an output from Adobe animate. Within that is the following pertinent code I added:

this.button.name = "button";
    this.button.on("click", function (a) {
        var address = document.getElementById("addrs").value
        var data ={address:address}
        console.log(data)
    }.bind(this));

Right now, I’m just displaying the information I typed into the TextInput('addrs') to the console to verify everything works.

I also established a connection to a Firebase database within the index.js and there I have the following code:

push(ref(db), {
  address: "1234 Maple Ln",
});

This is just a static placeholder for me to verify Firebase can receive information.

What I am trying to do is push the information that is now currently being saved to var data ={address:address} to Firebase instead of the static address: "1234 Maple Ln".

All of the tutorials I’ve found online use an HTML form. How do you do this when the submit button is in a different JavaScript file than where the push() is?

React Native app’s expo-sqlite callback not executed until app refresh

here is my app:


import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native'

import * as SQLite from "expo-sqlite";
import * as FileSystem from 'expo-file-system';
import { Asset } from 'expo-asset';


async function openDatabase() {
  if (!(await FileSystem.getInfoAsync(FileSystem.documentDirectory + 'SQLite')).exists) {
    await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + 'SQLite');
  }
  await FileSystem.downloadAsync(
    Asset.fromModule(require('./assets/banana-dict.db')).uri,
    FileSystem.documentDirectory + 'SQLite/banana-dict.db'
  );
  return SQLite.openDatabase('banana-dict.db');
}


export default function App() {
  const [ dicts, setDicts ] = useState([]);
  const [ db, setDb ] = useState({
    transaction: () => {
      return {
        executeSql: () => {},
      };
  }});

  const updateDicts = (a) => {
    setDicts(
      Object.fromEntries(a.map(({rowid, ...rest}) => [rowid, rest]))
    );
  }

  const fetchDicts = () => {
    console.log('fetch')

    db.transaction((tx) => {
      tx.executeSql(
        `select rowid, * from dicts;`,
        [],
        (_, { rows: { _array } }) => { console.log(_array); updateDicts(_array); }
      );
    });
  }

  useEffect(() => {
    openDatabase().then((value) => {
      setDb(value);
      fetchDicts();
    });
  }, []);

  return (
    <View style={{marginTop: 100}}>
      <Text>Open App.js to start working on your app!</Text>
      <Text>{JSON.stringify(dicts)}</Text>
    </View>
  );
}

banana-dict.db is a preexisting database I’m using for this site.
I’ve found that if I start the app and open it on my phone, the dicts (ie, results of a query on the db) do not appear. However, if I press r in the console for a refresh, the results appear immediately.
Anyone know why this is?

Data loading fails when inserting a file of products in my Node server.js

I am trying to load some product data into a Mongodb database before the Node server starts, I export the data loader in server.js. The failure is due to a duplicate key. First, I’m a newbie when it comes to Node. When I run the file on its own it loads the data without any issues. It only fails when I include in server.js

Here is the code for server.js

     const express = require("express");
     const app = express();

     const http = require("http");
     http.globalAgent = new http.Agent({
       keepAlive: true
     });
     const connectDbi = require("./config/prod-config");
     connectionDbi();

     const router = require("./routes/productRoutes");
     //Get the data loader here
     const loader = require("./loader/dbLoader");
     //Load the products here
     loader.productsLoader();

     app.use(express.json());
     app.use("/api/v2/products", router);

     app.listen(3000, () => console.log("Example app is listening on port 3000."));

Here is how the data is loaded

 const fs = require("fs");
 const Product = require("../models/Product");

   const products = JSON.parse(
      // Read products from a file
   );


   exports.productsLoader = () => {
     Product.create(products)
        .then(() => console.log("Products loaded"))
        .catch((err) => console.log(err));
   };

Unfortunately, the data starts getting loaded and then fails with a duplicate key after the first product is loaded. There is no other place except in server.js where this loader code is imported and used. How can a duplicate key arise from the loader? How can I prevent this from happening? Is there a better way to ensure this does not happen. I think this behavior may probably be because of the lifecycle process in Node, I’m quite new to Node.js

Here is the error:

Example app is listening on port 3000.
Connected to host localhost
MongoServerError: E11000 duplicate key error collection: products-db index: id_1 dup key: { 
product_id: 667070 }
at c:mongo-projectnode_modulesmongodbliboperationsinsert.js:51:33

React – how to update state from the prop of other library

I am using react-scrollmagic for scrolling effect.
When I use its component, there is a prop called progress,

{(progress, event) => (
   …
)}

Which I want to update my state currentProgress by.

How can I do it?

App.js

import "./styles.css";
import styled from "styled-components";
import { Controller, Scene } from "react-scrollmagic";
import React, { useState, useEffect } from "react";

const ClassToggleStyled = styled.div`
  .section {
    height: 100vh;
  }

  .test {
    transition: width 0.3s ease-out;
    width: 100px;
    height: 100px;
    background-color: red;
    margin: 0 !important;

    &.yellow {
      background-color: yellow;
    }
  }
  .zap {
    width: 100%;
  }
`;

export default function App() {
  const [currentProgress, setCurrentProgress] = useState(0);

  useEffect(() => {
    // I want to update the currentProgress  whenever the progress changed becausing of scrolling
    setCurrentProgress(0);
  }, []);

  return (
    <ClassToggleStyled>
      <div style={{ position: "fixed", top: 0 }}>
        Current Progress: {currentProgress}
      </div>
      <div className="section" />
      <div id="trigger" />
      <Controller>
        <Scene
          duration={200}
          classToggle="zap"
          triggerElement="#trigger"
          indicators={true}
        >
          {(progress, event) => (
            <div className="test">
              <div style={{ position: "fixed", top: 30 }}>
                Progress: {progress}
              </div>
              Pin Test {event.type} {progress}
            </div>
          )}
        </Scene>
        <Scene
          classToggle={[".test", "yellow"]}
          reverse={false}
          indicators={true}
        >
          <div>Toggle other class</div>
        </Scene>
      </Controller>
      <div className="section" />
    </ClassToggleStyled>
  );
}

Codesandbox
https://codesandbox.io/s/nifty-hermann-byrvz?file=/src/App.js

Variables are not being set inside the .then() part of a Promise? [closed]

psbt.addInput not being updated in promise. How to workaround it??

var psbt = new bitcoin.Psbt({ network: TESTNET }); var ran = [];
//grab one or multiple utxos  
getUTXO(amt_satoshi).then((utxo_arr) => {
for (let i = 0; i < utxo_arr.length; i++) {

pre_output += utxo_arr[i].value;

getTxHex(utxo_arr[i].txid).then((tx_hex) => {
  ran;
  ran.push(tx_hex);
  console.log("HEX", tx_hex);

psbt is a bitcoinjs object(transaction), addInput stays undefined.

  psbt.addInput({
    hash: utxo_arr[i].txid,
    index: i,
    nonWitnessUtxo: Buffer.from(tx_hex),
  });
});   

Customizing the MetaMask extension

I’m currently working on a little personal project where I need to interact a lot with my MetaMask wallet.

What I’m trying to accomplish is that whenever the MM popup is shown to confirm the action, that the Confirm is clicked automatically, but only when I’m connected to a specific page.

Now I know that this could raise security concerns, but I’m working on a separate machine with only one MM on it and only to be used with one specific page, so I’m not worried about security at this point.

Looking at the pagesource from the popup-page of MetaMask, I can extract the page by getting the value from this div:

<div class="confirm-page-container-summary__origin">https://thesite.io</div>

I have tried to modify the Notification.html to include a script which is run when the body is loaded. However when I tried it, the extension was automatically disabled. I had to “repair” it by downloading the extension again and importing my wallet again.

I’m guessing there’s some sort of checksum that happens so that any tampering results in disabling the extension.
Does anyone know if there’s a way to work around this issue?

Thanks

structuredClone() not available in TypeScript

I’m running node.js v17.2.0 and TypeScript v4.5.4. I’m trying to use structuredClone() on a Map, and it doesn’t seem to be working. ES2021 is targeted in tsconfig.json, and included in lib. Is this function just plain not available in TypeScript? Is there something else I need to include to get it?

@types/node is also installed, and I’ve made sure that it works in node.js environment.

structuredClone working in node.js environment

Firebase Firestore – React.js – Get Singular Document Values by ID (Make it Return json Object)

I know this is probably really simple – but I’m horrendous at JavaScript and can’t figure this out. Have been looking through other StackOverflow posts for a good hour and all “solutions” don’t seem to work.

I have the below function – which returns what’s shown in the image – but i’m not sure how to convert this into a json object that I can actually work with on the frontend.

Anyone know how to modify this in order to accomplish that?

  getTools = ({id}) => {
    let ref = this.write.collection('tools').doc(id)
    let results = []
    ref.onSnapshot(snapshot => {
      const id = snapshot.id
      const data = snapshot.data()
      results.push({...data, id})
      });
    return results
  }

enter image description here