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

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

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),
  });
});   

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

Problem with content overflowing container on mobile when using GSAP to achieve horizontal scroll

I’m having what I assume is a styling issue with GSAP. I’m working to replicate a webflow-esque horizontal scroll section, like this: https://demo.wplit.com/oxygen-horizontal-scroll/

It all works fine on desktop (and when I resize my browser down, for that matter):
enter image description here

But if you load it on mobile (or in responsive view, for that matter) the content ends up overflowing outside the site width:
enter image description here

I’m picking that it’s an issue with the GSAP script doing something differently on mobile, but I can’t pick what, and none of my CSS changes seem to help

Here’s my GSAP setup:

    gsap.registerPlugin(ScrollTrigger)
    
    let scrollContainers = document.querySelectorAll('.scroll-container');
    
    scrollContainers.forEach((scrollContainer) => {
     
        let gallery = scrollContainer.querySelector('.gallery');
        let sectionWrap = scrollContainer.querySelector('.gallery-section .gallery-wrapper');

        gsap.to(gallery, {
          x: () => -(gallery.scrollWidth - sectionWrap.offsetWidth) + "px",

          scrollTrigger: {
            start: "center center",
            trigger: gallery,
            invalidateOnRefresh: true,
            pin: scrollContainer,
            scrub: 1,
            anticipatePin: 1,
          }
        })
        
    }); 

Here’s a link to the live, public website: https://ehaus.co.nz/. Scroll down to the latest news section, and open responsive view (or load on mobile) to see the issue.

Any ideas how I can resolve this?

I get mime type error when I connect my react app(via vite.js) with django framework

recently I’m starting to make a web application with React and Django. I installed react with vite.js(because it seems so fast in the development environment). and I connected it to Django web framework and ran it. and I thought It would show basic react page(you know, dark page and favicon is revolving ) However, contrary to my expectations, It only shows blank and I checked the console.log. the error message was this : Refused to apply style from 'http://127.0.0.1:8000/assets/index.cd9c0392.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

so I googled it and figure out that is a problem with the path in most cases. but when I check the my index.html in build file, path seems fine. below is my build folder structure and index.html, can you tell me what is wrong with my code or logic or both? thx for reading , your help will be appreciated.

frontend
-dist => this is build folder
--assets
---index.cd9c0392.css
---favicon.21sd12.js
 .
 .    
 .
--index.html
-node_modules
-src
-index.html
.
.
.

index.html(in dist)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/assets/favicon.17e50649.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
    <script type="module" crossorigin src="/assets/index.3e288fda.js"></script>
    <link rel="modulepreload" href="/assets/vendor.dc18184a.js">
    <link rel="stylesheet" href="/assets/index.cd9c0392.css">
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

P.S I also get these following errors too which I assume same type of errors with above FYI.

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
vendor.dc18184a.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
main.jsx:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

Adding symbol in json files

I have not been able to add a “&” symbol in a “page-info.json” file as a text.

Example:

“copy”: “Click here to request design, video & layout support”

Please note:

The & symbol worked in other page-info.json project files before (React, Carbon).

However, for some reason, the “&” symbol appears (when using shift+7) in VSCODE, but is not appearing in the page preview itself.

I’ve tried using (backslash&) and (&amp 😉 already, but is not working either.

The only option that worked was using the command Control + Command + Spacebar keys in order to use the “&” as an emoji. The thing is … the emoji disappears when changing the responsive layout.

Could someone please help me?

Thanks in advance.

I needed to make a list in Javascript, but to no avail

I’m using an API and I wanted to extract the API URLs, for this I made a code, but only a url appears, I will give example of the JSON code of the API.
Not to mention that a title comes, then comes in order first title and then the URL

{
 "items": [
   "title":"YouTube",
   "url":"https://www.youtube.com/",
   "title":"Google",
   "url":"https://www.google.com/",
   "title":"Facebook",
   "url":"https://www.facebook.com/",
   "title":"Github",
   "url":"https://www.github.com",
   "title":"Microsoft",
   "url":"https://www.microsoft.com"
 ]
}

It’s not exactly these urls, I used it as an example.

I would like to extract this information and leave as follows:

[Title](Url)

I want it to look like this, because the title will turn blue and when you click it goes to the site URL.

My code that didn’t work out is this:

        const embed = new MessageEmbed()
            .setColor("#ffff00")
            .setDescription(`[${info.title}](${info.url})n`)

        await message.channel.send({
          embed: embed,
          buttons: btn
          });

This info.url is where you get the URL and info.title is where you get the title, only there’s only 1 problem, it takes only 1 title and 1 url, I would like you to take them all and form a list in The Discord Bot

This is the result of the code:
enter image description here

But I wanted it to look like this:
Youtube
Google
Facebook
Github
Microsoft

So that only youtube appears

And when you click on each title, be redirected to the site.

is it alright to have a ref on state (from a reducer) to avoid creating new callbacks?

I often have a use case where there is some state in reducer and it needs to be accessed in some callback (useCallback) as well

const [state, dispatch] = useReducer(reducer, initialState);
...
const handleAction = useCallback(()=>{
   // dependency on state 
},[])

to avoid running useCallbacks on every state change, I reach out for a ref and have the state assigned to it on every render

 stateRef.current = state;

and then where ever i have to use something from state in a callback, it is accessed from the stateRef. Is this a right way of doing it?