React Dynamic Components and Create Object

import React, { useState } from "react";

function Form() {
  const [components, setComponents] = useState(["1"]);

  function addComponent() {
    setComponents([...components, 1]);
    
  }

  const defaultState = [
    {
      title: "",
      desc: "",
    },
  ];

  const [form, setForm] = useState(defaultState);

  const handleChangeTitle = (e) => {
    setForm({
      title: e.target.value,
      desc: form.desc,
    });
  };

  const handleChangeDesc = (e) => {
    setForm({
      title: form.title,
      desc: e.target.value,
    });
  };
  return (
    <div>
      <div style={{ display: "flex" }}>
        <button onClick={addComponent}>+</button>
        {components.map((item, i) => (
          <>
            <div style={{ display: "flex" }}>
              <label>
                Title:
                <input
                  type="text"
                  name="title"
                  onChange={(e) => handleChangeTitle(e)}
                />
              </label>
              <label>
                Description:
                <input
                  type="text"
                  desc="desc"
                  onChange={(e) => handleChangeDesc(e)}
                />
              </label>
            </div>
          </>
        ))}
      </div>
    </div>
  );
}

export default Form;

Hi, I have a code like the one at the top. Pressing the “+” button on the page extracts a text input for title and description on the screen. This means that input numbers are increasing according to the user’s request. I want to print these inputs, which have more than one goal, in a single object (defaultState in form state). For example, if you want to use the user pressed the plus button 2 times and the view of the object should be as follows: {title:’Title:’1st title’, desc:’1.content’, title:’2.title’, desc:’2.content’, title:’3.title’, desc:’3.content’}

React newbie here: How do I export data from one component to another?

I have a component Header.js which has an input and button, when I hit button it will fetch data from a third party API. I want to then export the response to another component.

Header.js component as so:

import React, { useState } from 'react';
import Axios from 'axios';


const Header = () => {

    const [ticker, setTicker] = useState('');

    let url = `https://cloud.iexapis.com/stable/stock/${ticker}/quote?token=${process.env.REACT_APP_API_KEY}`;

    const getData = () => {

        Axios.get(url)
        .then((response) => {
            console.log(response.data);
            return response.data;
        })
        .catch(function(error) {
            console.log(error);
        })
    }

    const handleKeypress = (e) => {
        if(e.keyCode === 13) {
        getData();
        }
    }

    return (
        <div className='header'>
            <h1 id='brand'>Stock Tracker: {ticker}</h1>
                <div className='input-flow'>
                    <input onChange={e => setTicker(e.target.value)}
                    onKeyDown={handleKeypress}
                    className='ticker-input' 
                    type='text' 
                    placeholder='Ticker Symbol' 
                    maxLength='5' minLength='1'/>
                    <button className='add' 
                    onClick={getData}
                    type='submit'>Add</button>
                </div>
        </div>
    )
}

export default Header

Angular js Directive to Fire “click” event on pressing enter key on ANY element

I need to fire the click event using the enter key using a directive. I need it to be a directive because I would like to reuse it.

Ex: A div which has some onclick events bound to it, I will set focus on the div using the tabindex=”0″ and keyboard enter keydown to fire the click event.

Is this possible? I have tried below code for a directive but it doesnt work.

(function () {
'use strict';

angular
    .module('app.directives')
    .directive('enterKeyInput', enterKeyInput);

enterKeyInput.$inject = [];

/* @ngInject */
function enterKeyInput() {

    var directive = {
        restrict: 'AC',
        link: function (scope, element, attrs) {
            element.bind("keydown keypress", function (event) {
                if (event.keyCode === 13) {
                    element.click();
                }
            });
        }
    };

    return directive;
}

})();

Date Difference with date store in variable

I want to find date difference

    const d = new Date();
    const e = new Date("07,08,2025");
    document.getElementById("demo3").innerHTML = (parseInt(y)-parseInt(z));

in this i am able to find year difference.
Now if my date is stored in a variable ‘dob’ and i want to find difference between dob year and current year.

How to mock a 3rd party window object in vue test?

So i have a vue method that i need to test

in CheckoutButton.vue

createMidtransToken () {
  const card = this.$store.state.payment.creditCardPayload
  const options = {
        onSuccess: (response) => {
          // HANDLING SUCCESS
          const payload = {
            ...this.paymentTypeChoosen,
            token: response.token_id
          }
          this.payCheckout(payload)
        },
        onFailure: (response) => {
          // HANDLING ERROR
          const errorMessage = response.status_message
          this.$alertModal.show({
            show: true,
            type: 'error',
            title: 'Transaksi Dibatalkan',
            text: errorMessage,
            showButton: true,
            buttonText: 'Kembali',
            buttonEventExist: true,
            buttonEvent: () => {
              this.handleRouteError()
            }
          })
        }
      }
  window.MidtransNew3ds.getCardToken(card, options)
}

in CheckoutButton.spec.js

it('Should test createMidtransToken', () => {
    Object.defineProperty(window, 'MidtransNew3ds', {
      getCardToken: jest.fn()
    })

    wrapper.vm.createMidtransToken()
    expect(window.MidtransNew3ds.getCardToken).toHaveBeenCalled()
  })
})

and I get an error

● Testing component CheckoutButton with stage summary › Should test createMidtransToken

TypeError: Cannot read property 'getCardToken' of undefined
  362 |         }
  363 |       }
> 364 |       window.MidtransNew3ds.getCardToken(card, options)
      | ^
  365 |     },

How do I test the createMidtransToken method so the file test can run properly?

How to pass in a variable to Object.entries? [duplicate]

I have some collections of matching elements I am using to change an element’s class to a different class. However, I need to select the correct collection using the input to a function but when I give a variable to “Object.entries()”, it returns some other array. For example:

const classChanges_1 = { one: 'nine', two: 'eight', three: 'seven', ... };
    
/* works */
var pairs_1 = Object.entries(classChanges_1);
console.log(pairs_1);
    
/* doesn't work */
/* the "variable" variable is only here for the example but in my project it is input to a function */
var variable = "classChanges_1";
var pairs_2 = Object.entries(variable);
console.log(pairs_2);

How do I turn off wobbling for sweet alert2 [closed]

As soon as a sweetalert2 pops up, the exclamation point inside the circle starts wobbling and then stops, which can get annoying. What property do I apply to the JavaScript to turn that off?

Resources: https://cdn.jsdelivr.net/npm/sweetalert2@11

Code:

Swal.fire({
  icon: 'error',
  title: 'Oops...',
  text: 'Something went wrong!',
  footer: '<a href="">Why do I have this issue?</a>'
})
body {
  font-family: "Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", Helvetica, Arial, sans-serif; 
}
<!-- HTML is already in Developer Tools so there is no need for it, and this project can work without it.-->

Downloading multiple files from Google Cloud Storage in NodeJS

I am hosting a NodeJS app on Heroku in which users can upload their own images. I am hosting those images on Google Cloud Storage because Heroku will wipe them if they weren’t part of the deployment. So I check to see if the images are on the server. If they aren’t on the server, then they are requested from GCS.

When I try to download multiple images from a GCS Bucket to my host server, all image files downloaded will be the same as the last image in the request. If I have 1 image in the request, then the downloaded image will be correct. If I have more than one file, then only the last downloaded image is correct. The rest of the files have the correct filename, but the image downloaded for all of them are identical.

images.forEach((req) => {
  if (!fs.existsSync(`uploads/${req.imageName}`)) {
    storage.downloadImage(req.imageName).catch(console.error);                
  }
});

I have tried using async/await (awaiting the download) based on this post, but that yielded the same results. I’m not sure how to validate if a file on the server has completed a download.

how to generate a static function without ‘class{}’?

how do I generate something like:

function generator() {
static funct(){}
}

I think I’m wrong, but from what I understand the class {} method is built on top of function(){}, so it should have the same method. The point is that static methods don’t have a .prototype, and I’d like to know how they’re created via class {}

Angular error ‘can’t read undefined properties in sax.js: 222’ [closed]

step to detail:
I installed the xml2js dependency in my angular project which already had several installed
dependencies like sax and i couldn’t do the app build so i installed some dependencies for angular to recognize xml2js like:
npm install timers-browserify
npm install stream-browserify
furthermore i modified the tsconfig.json
but now I do ng serve the project and I get the following error:

 Uncaught TypeError: Cannot read properties of undefined (reading 'prototype')
    at sax.js:222
    at Object../node_modules/xml2js/node_modules/sax/lib/sax.js (sax.js:1565)
    at __webpack_require__ (bootstrap:79)
    at Object.<anonymous> (parser.js:9)
    at Object../node_modules/xml2js/lib/parser.js (parser.js:381)
    at __webpack_require__ (bootstrap:79)
    at Object.<anonymous> (xml2js.js:12)
    at Object../node_modules/xml2js/lib/xml2js.js (xml2js.js:39)
    at __webpack_require__ (bootstrap:79)
    at Module../src/app/**/**/**/**.component.ts (main.js:5014)
    ```

React: Can’t create li element because Promise();

I cannot figure out how to access this Promise object. How to map this promise? And why my async/await function is returning a promise and not a result object?
Any feedback appreciated.

Promise {<pending>}
 [[Prototype]]: Promise
 [[PromiseState]]: "fulfilled"
 [[PromiseResult]]: Array(2)
   0: "hey"
   1: "bye"
   length: 2[[Prototype]]: Array(0)
import { io } from "socket.io-client";
import { useState, useEffect } from "react";
function App() {
  const [text, setText] = useState("");
  const [socket, setSocket] = useState();
  const [chat, setChat] = useState([]);
  useEffect(() => {...}, []);
***//getting previous chat for new users.***

  useEffect(async () => {
    let mounted = true;
    const response = await fetch("http://localhost:4000/main_chat").then(
      (res) => {
        if (mounted) {
          setChat(res.json());
        }
      }
    );

    return () => (mounted = false);
  }, []);

  useEffect(() => {...},[socket]);

  const handleClick = () => {
    socket.emit("sentFromClient", text);
  };
  return (
    <div>
      <ul>{console.log(chat)}</ul>
      <input value={text} onChange={(e) => setText(e.target.value)}></input>
      <button onClick={() => handleClick()}>enter</button>
    </div>
  );
}

export default App;

I am writing a function to modify the objects inside. 1 problem: One of the object properties is not the last element, seems like it needs to array?

const recordCollection = {
    2548: {
      albumTitle: 'Slippery When Wet',
      artist: 'Bon Jovi',
      tracks: ['Let It Rock', 'You Give Love a Bad Name']
    },
    2468: {
      albumTitle: '1999',
      artist: 'Prince',
      tracks: ['1999', 'Little Red Corvette']
    },
    1245: {
      artist: 'Robert Palmer',
      tracks: []
    },
    5439: {
      albumTitle: 'ABBA Gold'
    }
  };
  
  **// Only change code below this line**

  function updateRecords(records, id, prop, value) {
     **2548 Jon Bon Jovi** 
        if (value === "") { 
        delete records[id].artist;
        delete records[id].tracks;
    } 

      **//5439 ABBA**
    else if (prop === 'tracks') {
        recordCollection[id].tracks = [];
        records[id].tracks.push(value);

This is the error iMessage I am getting in regards to the ABBA song:
After updateRecords(recordCollection, 5439, “tracks”, “Take a Chance on Me”), tracks should have the string Take a Chance on Me as the last element.I Think they want me to Create an Array? But I thought the Abba song was the last element

       **// 5439 ABBA**
    } else if (prop === "artist") {
        records[id].artist = value;

      **// 1245 Robert Palmer**
    } else if (prop === "tracks") {
        records[id].tracks.push(value);
      
      **// 1245 Robert Palmer**
    } else if (prop != "tracks") {
        records[id].albumTitle = "Riptide";

    }
    
    
    return records;
  }

How to edit several audio clips into a larger audio clip for download in one audio file (HTML, JS)?

How can I mix several audio clips together in order to make one assembled audio file for download. Like audio Mad Libs. Remember Mad Libs?

Here’s what I’ve got so far (it’s not much):

var audio = document.getElementById('mad-libs')
var audio1 = document.getElementById('1')
var audio2 = document.getElementById('2')
var audio3 = document.getElementById('3')
var audio4 = document.getElementById('4')
var audio5 = document.getElementById('5')
var audio6 = document.getElementById('6')
var record = document.getElementById('record')
var mediaRecorder = null
var recording = false
var chunks = []

recordAndStore(audio1)

function recordAndStore (slot) {
  navigator.mediaDevices.getUserMedia({
    audio:true
  }).then(function (stream) {
    mediaRecorder = new MediaRecorder(stream)
    record.addEventListener('click', function (event) {
      if (recording == false) {
        recording = true
        mediaRecorder.start()
        record.textContent = '⏹️ Stop'
      } else {
        recording = false
        mediaRecorder.stop()
        record.textContent = '⏺️ Record'
      }
      mediaRecorder.ondataavailable = function (data) {
        var audioURL = window.URL.createObjectURL(data.data)
        slot.src = audioURL
      }
    })
  }).catch(function (error) {
    console.log(error)
  })
}
audio.hidden {
  display: none;
}
button {
  font-size: 1.35em;
  padding: .25em .5em;
  cursor: pointer;
}
<h1>Mad Libs</h1>
<p>Get Ready To Record Your Mad Libs</p>
<p>Click the record button and say a "noun," "verb," "adjective," or anything else you're prompted for »</p>
<h4 id='prompt'>Common Noun</h4>
<button id="record">⏺️ Record</button>
<audio id="mad-libs" src='audios/mad-libs.m4a' controls class='hidden'></audio>
<audio id='1' controls></audio>
<audio id='2' controls></audio>
<audio id='3' class='hidden'></audio>
<audio id='4' class='hidden'></audio>
<audio id='5' class='hidden'></audio>
<audio id='6' class='hidden'></audio>
<button id="download">Download</button>

<!--

This is the mad libs story...

Once upon a time there was a king with a great big
______ (common noun).

And every morning he took it out on the royal balcony
and ______ (verb, past tense) it for at least 3 hours.

This exhausted the king, and he was very ______
(adjective) to begin with.

The people had gotten very ______ (adjective) with the
king's morning routine.

So they gathered all their ______ (noun, plural),
stormed the castle and ______ (verb, pased tense) the
king.

THE END


-->

I’d like the user to be able to record their prompts (noun, verb, adjective, etc), and then play them back in the context of the mad libs story (which is recorded ahead of time for them in an animated voice).

Plus! Importantly, I want to let them download their creation with a download button.

I’ve gotten lost in Array Buffers and Blobs, and I can’t make much sense of how to do this. Am I better off trying to use WASM with ffmpeg? Or Media Recorder API? Help would be awesome : )