How to properly structure logic in redux?

There is an action to update an item:

reducers: {
  ITEM_UPDATED: (state) => {
    ...someCode...
  }
}

Then it becomes necessary to update not one element, but several, which solution would be more correct here:

  1. Create thunk for updating several elements and from there call the update of each one by one:
const updateItems = () => (dispatch) => {
  const items = axios.get('...');
  items.forEach(( item ) => dispatch(ITEM_UPDATED, item))
}
  1. Move the handler for updating the element into a separate function and reuse it.
const handleItemUpdated = (state) => {
  ...
}

reducers: {
  ITEM_UPDATED: (state, item) => handleItemUpdated(state, item);
  ITEMS_UPDATED: (state, items) => {
    items.forEach(( item) => handleItemUpdate(state, item));
  }
}

How to use spinner and then display a component after submit button?

So I am building this project using ChakraUI and ReactJS.
So in this UploadImage component, what I wanna do is, when you choose a file and then hit the Upload button, the spinner will load while the data is being fetched. After it is finished fetching the data, the loading is going to be false and it will render the component.
But currently it is rendering component initially and after you submit the file it renders the DisplayImage component.
So how to implement the spinner component properly?

My current code is the following:

function UploadImage() {
  const [selectedFile, setSelectedFile] = useState(null);
  const [error, setError] = useState(null);
  const [inputImage, setInputImage] = useState(null);
  const [outputImage, setOutputImage] = useState(null);
  const [isSubmit, setIsubmit] = useState(false);
  const [isLoading, setIsloading] = useState(true);
  const fileUploadHandler = () => {
    const fd = new FormData();
    fd.append("file", selectedFile, selectedFile.name);
    axios
      .post(`/api/predict`, fd)
      .then((res) => {
        setIsubmit(true);
        setInputImage(res.data.image);
        setOutputImage(res.data.mask);
        selectedFile(null);
        setError(null);
        setIsloading(false);
      })
      .catch((error) => {
        console.log(error);
        setSelectedFile(null);
        setError(error.data);
      });
  };

  const fileData = () => {
    if (selectedFile) {
      if (
        selectedFile.type === "image/jpeg" ||
        selectedFile.type === "image/png"
      ) {
        return (
          <div>
            {error && <div>file too large!!</div>}
            <Button
              colorScheme='teal'
              size='sm'
              onClick={() => fileUploadHandler()}
            >
              Upload!
            </Button>
          </div>
        );
      } else {
        return (
          <div>
            <h4>Please choose an image to upload</h4>
          </div>
        );
      }
    } else {
      return (
        <div>
          <h4>Choose Photos</h4>
        </div>
      );
    }
  };

  return (
    <div>
      <input type='file' onChange={(e) => setSelectedFile(e.target.files[0])} />
      {fileData()}
      {isSubmit && isLoading === false ? (
        <DisplayImage inputImage={inputImage} outputImage={outputImage} />
      ) : (
        <Spinner />
      )}
    </div>
  );
}
export default UploadImage;

Select an element having conditional render, on the beginning of the code in react.js

I’ve made 2 popup div in react. On the first page load, first popup is visible but i’ve set the opacity of second popup to 0. I’m handling this with a class ‘hide’. And i’m placing this hide class on the second popup based on a state. What i’m trying to achieve here is that i want to select a button having a class of ‘evil-btn’ that is present on the second popup. And add some event listeners to that button. But i’m not able to select that button, as a global variable. It’s returning null. So can anyone suggest me a way how i can select this button in the global scope..?? Below is the code for my Popup component.

import React, { useEffect, useRef, useState } from "react"

function Popup() {
  const [isSecondActive, setIsSecondActive] = useState(false)
  const [firstBtn, setFirstBtn] = useState(true)
  const [secondBtn, setSecondBtn] = useState(false)
  const container2_ref = useRef(null)
  console.log(container2_ref)

  const OFFSET = 100

  const handleMouseOver = (e) => {
    console.log(e.target.innerText)
    if (e.target.innerText === "NO") {
      setFirstBtn(!firstBtn)
      setSecondBtn(!secondBtn)
    }
  }

  const handleClick = (e) => {
    console.log(e.target.innerText)
    if (e.target.innerText === "YES") {
      alert("I Knew You Were Dumb!!")
    }
  }

  const handleSecondClick = (e) => {
    console.log(e.target.dataset.name)
    if (e.target.innerText === "YES") {
      alert("I Knew You Were Dumb!!")
    }

    if (e.target.innerText === "NO") {
      alert(
        "I hate you, you clicked me so hard, I'm going and closing this window"
      )
      // window.close()
    }
  }

  var evilBtn = document.querySelector(".evil-btn")

  document.addEventListener("mouseover", (e) => {
    const x = e.pageX
    const y = e.pageY
    const buttonBox = evilBtn.getBoundingClientRect()
    // console.log("x", x)
    // console.log("y", y)
    let horizontalDistanceFrom = distanceFromBtn(
      buttonBox.x,
      x,
      buttonBox.width
    )
    let verticalDistanceFrom = distanceFromBtn(buttonBox.y, y, buttonBox.height)

    const verticalOffset = buttonBox.height + OFFSET / 2
    const horizontalOffset = buttonBox.width + OFFSET / 2

    if (
      Math.abs(
        horizontalDistanceFrom <= horizontalOffset &&
          Math.abs(verticalDistanceFrom <= verticalOffset)
      )
    ) {
      setButtonPosition(
        buttonBox.x + (horizontalOffset / horizontalDistanceFrom / 2) * 10,
        buttonBox.y + (verticalOffset / verticalDistanceFrom / 2) * 10
      )
    }
  })

  const setButtonPosition = (left, top) => {
    console.log(evilBtn)
    evilBtn.style.left = `${left}px`
    evilBtn.style.top = `${top}px`
  }

  const distanceFromBtn = (buttonPosition, mousePosition, buttonSize) => {
    return buttonPosition - mousePosition + buttonSize / 2
  }

  return (
    <div className='container'>
      <div className='popup'>
        <section className='section-top'>
          {/* CONTAINER 2 START */}
          {
            <div
              ref={container2_ref}
              className={`container second-container container-2 ${
                isSecondActive ? "" : "hide"
              }`}
            >
              <div className='popup'>
                <section className='section-top'>
                  <button
                    onClick={() => setIsSecondActive(false)}
                    className='close-btn'
                  >
                    X
                  </button>
                </section>
                <section className='section-middle'>
                  <h2 className='heading-msg'>
                    Do you really want to quit? But first tell me are you
                    dumb..??
                  </h2>
                </section>
                <div className='btn-containers'>
                  <button
                    data-name='second-yes'
                    onClick={handleSecondClick}
                    className='btn yes-2'
                  >
                    YES
                  </button>
                  <button
                    data-name='second-no'
                    onClick={handleSecondClick}
                    className='btn no-2 evil-btn'
                  >
                    NO
                  </button>
                </div>
              </div>
            </div>
          }
          {/* CONTAINER 2 END */}
          <button onClick={() => setIsSecondActive(true)} className='close-btn'>
            X
          </button>
        </section>
        <section className='section-middle'>
          <h2 className='heading-msg'>Are You Dumb..??</h2>
        </section>
        <div className='btn-container'>
          <button
            onClick={handleClick}
            onMouseOver={handleMouseOver}
            data-name='first-yes'
            className='btn yes-1'
          >
            {firstBtn ? "YES" : "NO"}
          </button>
          <button
            onClick={handleClick}
            onMouseOver={handleMouseOver}
            data-name='first-no'
            className='btn no firstNo'
          >
            {secondBtn ? "YES" : "NO"}
          </button>
        </div>
      </div>
    </div>
  )
}

export default Popup

Toogle active class using getElementById

I am trying to change class from none to active using document.getElementById but it is just adding active not removing it.

page.html

function toggleIt() {
  let collapseModel = document.getElementById(`collap_id`).className += "content active";
  collapseModel[0].classList.toggle("active")
}
.content {
  padding: 10px 20px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}

.content.active {
  padding: 10px 20px;
  display: block;
  overflow: hidden;
  background-color: #f1f1f1;
}
<button onclick="toggleIt();">Open</button>

<div class="content" id="collap_id">
  Here will be all the details
</div>

When I click on toggle it then it is opening but not closing , it is also showing "Uncaught TypeError: Cannot read properties of undefined (reading 'toggle')"

I have tried many times but it is not toggling.

Javascript module in nuxt [duplicate]

i am learning how to build a js module and upload to npm and install back into nuxt and try to use the function inside. trying to understand the proccess to build a module. but i keep getting error, i try to simple the module much as possible can anyone tell me what i miss out ?

module – dayuntilxmas
github enter link description here

dayuntilxmas

  • README.md
  • index.js
  • package.json

index.js

export function greetPerson(name) {
    return `Hello ${name}`;
}

nuxt/pages/index.vue

<template>
    <div>
        <h1>this is plugins test framework</h1>
    </div>
</template>

<script>
    import {
        greetPerson
    } from 'dayuntilxmas'

    export default {
        data() {
            const greet = greetPerson()
            return {
                greet
            }
        },
        mounted() {
            console.log(this.greet('jade'))
        }
    }
</script>

so what do i missout ? i see some said need to include a html file inside module, but isit needed for some reason ?

the error it return was “Unexpected token ‘export'”

How to get the first day of the next month in JavaScript

I need to get the first day of the next Month for a datePicker in dd/mm/yyyy format.

how can i do it?

i have this code :

var now = new Date();
if (now.getMonth() == 11) {
  var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
  var current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}

console.log(current)

but it’s give this :

Sat Jan 01 2022 00:00:00 GMT+0200 

i need it like this 01/01/2022

any help here =)?

Why well-know symbols are in Symbol and not in Reflect API

I don’t understand one thing about well-known symbols in Javascript. What is the reason of putting those well-known symbols into Symbol instead of Reflect API? For me seems that the right place for them is the Reflect API as the Reflect API is made for metaprogramming, particularly for reflection and particularly for introspection and self-modification? Does anyone knows the reason of doing so?

Change elements display order after click event – javascript

After i click on Calculate button “Reset” button appears below it, but i want to change the display styles how they both appear after the click event. I want them side by side and not on top of each other (picture in link represents the idea) I tried doing it by toggling a class after click, but in that way i could change only one element appearance. What would be the best way to do it?
Button order example

HTML code

<div class="container">
        <header>
          <div class="h1-background">
            <h1 class="h1">Tip calculator</h1>
          </div>
        </header>
        <div class="text">
    
          <p>How much was your bill?</p>
          <form name="theForm3">
            <input class="input-bill" placeholder="Bill Amount $">
            <p>How big tip will you give?</p>
            <!-- DROP DOWN-->
            <div class="select">
              <select class="percents">
                <option value="1">Nothing</option>
                <option value="0.5">5%</option>
                <option value="0.10">10%</option>
                <option value="0.15">15%</option>
                <option value="0.20">20%</option>
                <option value="0.30">30%</option>
    
              </select>
            </div>
          </form>
          <!-- AFTER DROP DOWN-->
          <p>How many people are sharing the bill?</p>
          <input class="input-people" placeholder="Number of people">
          <button onclick="calculateTip(), changeStyle()" class=" button center button-calc"
            type="button">Calculate
          </button>
    
          <button onclick="" class=" button center reset-button" type="button">Reset
          </button>

JS CODE

"use strict";
const buttonCalc = document.querySelector(".button-calc");
function calculateTip() {
    //Selectors
    const inputBill = document.querySelector(".input-bill").value;
    let inputPeople = document.querySelector(".input-people").value;
    const percents = document.querySelector(".percents").value;
    //Event listeners

    //validate input
    if (inputBill === "" || percents == 0) {
        alert("Please enter values");
        return;
    }



    //Check to see if this input is empty or less than or equal to 1
    if (inputPeople === "" || inputPeople <= 1) {
        inputPeople = 1;

        document.querySelector(".each").style.display = "none";

    } else {
        document.querySelector(".each").style.display = "block";
    }


    //Functions
    let total = (inputBill * percents) / inputPeople;
    console.log(total);
    //round to two decimal places
    total = Math.round(total * 100) / 100;
    //next line allows us to always have two digits after decimal point
    total = total.toFixed(2);
    //Display the tip

    // Display alert i there is no TIP
    if (percents == 1) {
        alert(`There is no tip, you must pay only the bill $${total}`)
        return;
    }


    document.querySelector(".reset-button").style.display = "block";
    document.querySelector(".totalTip").style.display = "block";
    document.querySelector(".tip").innerHTML = total;

}


function changeStyle() {
    let container = document.querySelector(".container");
    container.style.height = "400px";
    event.preventDefault();
}


//Hide the tip amount on load
document.querySelector(".reset-button").style.display = "none";
document.querySelector(".totalTip").style.display = "none";
document.querySelector(".each").style.display = "none";

Adding screen share option webrtc app. unable to get on other users

i was adding screen share funcanlity to my app but its is not working .. its only show screen share on my side but not on other user.
here is code :-
try{
navigator.mediaDevices.getDisplayMedia({
video: true,
audio:true
}).then(stream => {
const video1 = document.createElement(‘video’);
video1.controls = true;
addVideoStream(video1,stream)

    socket.on('user-connected', userId =>{
        const call = peer.call(userId, stream)
        stream.getVideoTracks()[0].addEventListener('ended', () => {
            video1.remove()
          });
        call.on('close', () => {

        })  
    })
        stream.getVideoTracks()[0].addEventListener('ended', () => {
          video1.remove()
        });
      });
    }catch(err) {
        console.log("Error: " + err);
    }

Text editor in javascript (like notepad)

Hello friends I am learning javascript but I have a question that how can we make a text editor like notepad in javascript by which we can open a text file and edit and save it. With the help of javascript,html and css.

PLEASE ANSWER MY QUESTION

What is difference between these Three?

class AppError extends Error{
    constructor(message,statusCode){
        super(message)
        this.statusCode = statusCode
    }
}

AND

class AppError extends Error{
    constructor(message,statusCode){
        super(message)
        this.message=message
        this.statusCode = statusCode
    }
}

AND

class AppError{
    constructor(message,statusCode){
        this.message = message
        this.statusCode = statusCode
    }
}

I am woking on nodeJs project using mongo.During error handling I created this class but not understading difference between these.

save as json format from Web Speech API Transcript

I am using web speech recognition API in Chrome to get transcripts & store in a string array variable(called notes). I would like to save the full transcripts as json so I can easily use it later.

Currently my project has html, css & script.js, the transcripts are stored in localStorage. May I know how should I work to save the transcript as json? Or if there are any useful links?

I watched the related videos(
https://youtu.be/T7s3st6xfpA?t=205
), result.js will be created if i assign the info in a variable (notesInfo) & call

node saveFile.js

saveFile.js

  const notesInfo = {
      date:'1.12.2021', content:'How are you'
  }

  const fs = require('fs');

  const saveData = (notesInfo) => {
        const finished = (error) => {
            if(error){
              console.error(error)
              return;
            }
        }

        const jsonData = JSON.stringify(notesInfo)
        fs.writeFile('result.json', jsonData, finished)
  }

  saveData(notesInfo)

result.json

{"date":"1.12.2021","content":"How are you"}

But this is suitable for assigning a predictable data ({“date”:”1.12.2021″,”content”:”How are you”})into a variable (notesInfo). But I want my string array variable (notes) which generated from Web Speech Recognition can be saved in a new json file automatically when i start using speech Recognition in my web brower. I worked for days but still have no ideas.

Thank you for your kindness!

How do I get around SPA framework undoing inserted CSS style?

I have a site and it uses Svelte. I inject custom CSS styling to certain rows of the table, but the styles seems get swapped into totally different rows as soon as the Table get updated with new data.

I tried to debug this issue using Devtools. From what I observe, Svelte reuse tds and change their text contents

The CSS style is injected using Javascript like this,

const tds = tr.getElementsByTagName("td");

tds[1].style.background = "black"