Assign ref dynamically inside concat in react render

I have an array of objects which I create on pressing the add button.The add handler function is as below.

const [inputList,setInputList] = useState([])

const elref=useRef(null)

const add = () => {
setInputList([...inputList,
<div>
<EditContainer

onTextChnage={handleChange}
ref={elref}
/>

</div>
}])}

This create multiple EditContainer elements all of which share the same ref.How can I create refs like this on the fly for a dynamic array of Object which is a state

Cannot read properties of undefined (reading ‘split’) React.js

I am building a react app and when I try to load up the application in the browser, I get the error in the title. Command I am using to start the application : swa start http://localhost:3000 –run “npm start –javascript” –api-location src/api. Looking through the stack trace this seems to be related to a line in the Mongoose browser.umd file that is trying to split t.versions.node :

e.noop=function(){},e.errorToPOJO=function(t){if(!(t instanceof Error))throw new Error(“error must be instanceof Error.”);var e,r={},o=n(Object.getOwnPropertyNames(t));try{for(o.s();!(e=o.n()).done;){var i=e.value;r[i]=t[i]}}catch(t){o.e(t)}finally{o.f()}return r},e.nodeMajorVersion=parseInt(t.versions.node.split(“.”)[0],10)}).call(this,r(10))},function(t,e,r){“use strict”;(function(t){

This is not my code and I am unsure exactly what it is doing or why the t.versions.node is undefined. My node version is 14.16.1, mongoose version is 5.11.1. Stack trace included below :

Uncaught TypeError: Cannot read properties of undefined (reading 'split')
    at Object.<anonymous> (browser.umd.js:220)
    at Object.<anonymous> (browser.umd.js:220)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:1012)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:1009)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:308)
    at Object.<anonymous> (browser.umd.js:425)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:756)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:973)
    at Object.<anonymous> (browser.umd.js:977)
    at r (browser.umd.js:1)
    at Object.<anonymous> (browser.umd.js:973)
    at r (browser.umd.js:1)
    at browser.umd.js:1
    at browser.umd.js:1
    at browser.umd.js:1
    at Object../node_modules/mongoose/dist/browser.umd.js (browser.umd.js:1)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Module.<anonymous> (App.js:38)
    at Module../src/api/app_functions/func_mongo_create_connection.js (func_mongo_create_connection.js:132)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Module../src/api/az_func_wfd/index.mjs (index.mjs:1)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Module.<anonymous> (CollectLoginInfo.js:59)
    at Module../src/component/Configuration.js (Configuration.js:368)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Module.<anonymous> (App.css?dde5:82)
    at Module../src/App.js (App.js:38)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Module.<anonymous> (index.css?bb0a:82)
    at Module../src/index.js (index.js:18)
    at __webpack_require__ (bootstrap:856)
    at fn (bootstrap:150)
    at Object.1 (ui_carmax_logo.PNG:1)
    at __webpack_require__ (bootstrap:856)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1

I also believe this might have something to do with my import/exports of functions throughout my code, but that is partially a guess. Any help is appreciated.

Don’t have permission to read data on Onclick in React Firebase Firestore

I am creating a button that loads more documents from firestore database but the problem arises that I am able to do it in useEffect and set the state to the data. When I try to do the same thing in on click event handler it gives me the error that you don’t have sufficient access as I am logged in I have the access so I was able to get the data from firestore.
Here is some code::

import React, { useEffect, useState } from "react";
import Container from "@mui/material/Container";
import Box from "@mui/material/Box";
import Typography from "../../subcomponents/Typography";
import Adcard from "../../subcomponents/Marketplace/Adcard";
import Button from "@mui/material/Button";
import Pagination from "../../subcomponents/Marketplace/PaginationComponent";
import { db } from "../../config/Config";

function Adspace({ Products }) {
  const [data, setData] = useState(null);
  const [lastDoc, setlastDoc] = useState();
  useEffect(() => {
    return db
      .collection("Products")
      .orderBy("MonthlyRate", "asc")
      .limit(2)
      .get()
      .then((snapshot) => {
        const ProductData = snapshot.docs.map((doc) => doc.data());
        /* snapshot.docs.forEach((doc) => {
          ProductData.push({ ...doc.data(), id: doc.id });
          setData(ProductData);
        }); */
        setData(ProductData);

        const lastDoc = snapshot.docs[snapshot.docs.length - 1];
        setlastDoc(lastDoc);
      });
  }, []);
  console.log(data);
  console.log(Products);
  const fetchData = () => {
    db.collection(Products)
      .orderBy("MonthlyRate", "asc")
      .startAfter(lastDoc)
      .limit(1)
      .get()
      .then((snapshot) => {
        const ProductData = snapshot.docs.map((doc) => doc.data());
        setData((PrevData) => [...PrevData, ProductData]);
        const lastDoc = snapshot.docs[snapshot.docs.length - 1];
        setlastDoc(lastDoc);
      });
  };
  return (
    <div>
      <Container component="section" sx={{ mt: 8, mb: 4 }}>
        <Typography variant="h4" marked="center" align="center" component="h2">
          Rent Machines
        </Typography>
      </Container>
      <Box
        sx={{
          m: 8,
          display: "flex",
          flexWrap: "wrap",
          justifyContent: "flex-start",
        }}
      ></Box>
      <Container
        component="section"
        sx={{ mt: 8, mb: 4, display: "flex", justifyContent: "center" }}
      >
        {/*  {data !== null ? <Adcard /> : ""} */}

        {data !== null
          ? data.map((doc) => {
              if (doc.Type === Products) {
                return <Adcard data={doc} state={Products} key={doc.id} />;
              } else if (Products === "All") {
                return <Adcard data={doc} state={Products} />;
              }
            })
          : ""}
      </Container>
      <Box textAlign="center">
        <Button variant="contained" onClick={fetchData}>
          Load More
        </Button>
      </Box>
    </div>
  );
}

export default Adspace;

And here is firestore database rules for this collection

 match /Products/{userid}{
        allow create:if request.auth.uid!=null
      allow read: if request.auth.uid!=null
      allow write:if request.auth.uid==userid
      allow delete:if request.auth.uid!=null
    }

AJAX, using onreadystatechange() but still not working

I have been working on a XML, HTTP communication , and I do not understand why my code seems to have some type of error. When sending a get request, sometimes it fails to get response or even to send to the server(I believe, as no message is shown). When I include alerts it does work. I understand this is due to asynchronous programming, as the alerts give more time to the operation. But even so, I am working with onreadystatechange() so I do not understand. Here is the code:

<script  type ="text/javascript">

const xhr = new XMLHttpRequest();
function sendData() {
const getEnter = document.getElementById('p_input').value;
const cont = document.getElementById('cont');
var url = "http://192.168.1.132:4344?";
url += getEnter;

xhr.onreadystatechange = () => {
    if(xhr.readyState==4 && xhr.status==200){
        console.log("success");

    }
}
xhr.open('GET',url,true);
cont.textContent ="processing";
xhr.send();
}
</script> 

I am calling this function on the onClicked event of a button. It would be excellent if someone knew how to fix this

return value remains undefined even when timed out for 10 seconds

I had an issue where I needed to return the response of an async function which kept being returned as undefined. So I decided to use setTimeout() before trying to use it. It still doesn’t seem to work. Can someone explain why?

My attempt:

insertUser = (req,res) => {
    var record = {
        'handle': req.body.handle,
        'name': req.body.name,
        'password': req.body.password
    };
    var response;
    createUser(record, response)
    setTimeout(() => {
        console.log(response);
    },10000)
};

createUser = (record, response) => {
    users.insertOne(record, function(err, result){
        if(err){
            response = {'code': 404, 'message': 'Something went wrong. Message: ', err} 
        }else{
            response = {'code': 200, 'message': result.insertedId}
        }
    })
    setTimeout(() => {
        console.log(response)
    }, 1000);
};

Why unary operator before exponentiation expression in JavaScript cannot be evaluated? [duplicate]

I noticed that expression like “-3**2” is considered ambiguous in JavaScript. For example, in Chrome, the error is thrown as “Uncaught SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence.”

From the perspective of compiler (specifically, parser I think) or syntax designer, why this input is not allowed? If I were the designer of the compiler, maybe I would just assign a higher precedence to unary operator, or the other way, instead of throw an error.

how to change navigation focus view of v-date-picker with manual trigger

i made vue date range picker manually using v-list and v-date-picker :

<v-card width="600" elevation="1" rounded>
    <v-container class="pa-0" fluid>
      <v-row dense no-gutters>
        <v-col cols="3" style="height: 100%">
          <v-list>
            <v-list-item-group v-model="select">
              <v-list-item v-for="(item, i) in items" :key="i">
                <v-list-item-content>
                  <v-list-item-title v-text="item.time" @click="tes(item.duration)"></v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list-item-group>
          </v-list>
        </v-col>
        <v-divider></v-divider>
        <v-col cols="9">
          <v-date-picker ref="tes" v-model="dates" range full-width>
            <template>
              <v-container class="pa-0">
                <v-row>
                  <v-col cols="6"><YBtn block secondary>Cancel</YBtn></v-col>
                  <v-col cols="6"><YBtn block>Apply</YBtn></v-col>
                </v-row>
              </v-container>
            </template>
          </v-date-picker>
        </v-col>
      </v-row>
    </v-container>
</v-card>

and my script :

export default {
data() {
    return {
    select: { time: 'Today', duration: 'today' },
    items: [
        { time: 'Today', duration: 'today' },
        { time: 'Yesterday', duration: 'yesterday' },
        { time: 'This Month', duration: 'thismonth' },
        { time: 'This Year', duration: 'year' },
        { time: 'Previous Month', duration: 'previousmonth' }
    ],
    dates: [this.$moment().format('YYYY-MM-DD')]
    }
},

methods: {
    tes(e) {
    switch (e) {
        case 'yesterday':
        this.dates = this.$moment().subtract(1, 'days').format('YYYY-MM-DD')
        break
        case 'thismonth':
        this.dates = [
            this.$moment().startOf('month').format('YYYY-MM-DD'),
            this.$moment().endOf('month').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        case 'year':
        this.dates = [
            this.$moment().startOf('year').format('YYYY-MM-DD'),
            this.$moment().endOf('year').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        case 'previousmonth':
        this.dates = []
        this.dates = [
            this.$moment().startOf('month').subtract(1, 'months').format('YYYY-MM-DD'),
            this.$moment().endOf('month').subtract(1, 'months').format('YYYY-MM-DD')
        ]
        console.log(this.dates)
        break
        default:
        this.dates = this.$moment().format('YYYY-MM-DD')
        break
    }
    }
}
}

when i click on previous month, it succesfully change v-date-picker value to the selected previous month. but, the navigation still in current month. how do i change v-date-picker navigation focus to selected previous month?

as you can see there, the focus navigation at december. what i want when i click prevous month. it showing november, which is the previous selected month

How do I create a custom Form with FormData and upload to a server as PHP

If you wanted to upload randomText - 5994 text to a PHP server without the client using a <form> and data was sent in the background, how would you do it?
I guess this should be my code…

let xhr = new XMLHttpRequest();
xhr.open("log.php","POST");
//correct after this line.
xhr.send('{"name":"Sample Form Data","age":".."}');
xhr.close();

The code should send a request + data and the PHP code will do the rest.
This is the PHP code.

$name = $_POST["name"];
$age = $_POST["age"];
echo "client: ".$name."age".$age."yrs";

Native Javascript click event not working on icon in button

I have a button in my HTML + Tailwindcss page like so:

<div class="fixed bottom-4 right-4 z-10">

    <button
        id="button-fab-anchor"
        class="z-50 whitespace-nowrap flex items-center px-3.5 py-2 rounded-full shadow-xl
           outline-none focus:outline-none border-t border-b border-transparent
           combo-primary hover:bg-primary-contrast active:bg-primary-contrast"
    >
        <span class="z-40 icon-inverse-primary text-lg text-center">
            <i id="up-icon" class="fal fa-chevron-up"></i>
            <i id="down-icon" class="fal fa-chevron-down hidden"></i>
        </span>

    </button>

    <ul id="button-fab-list" class="absolute bottom-full right-0 flex flex-col justify-end hidden">
        <li> Buttons here... </li>
    </ul>

</div>

On the page I have the following JS:

document.addEventListener("DOMContentLoaded", function(event) {

    const btnAnchor = document.getElementById('button-fab-anchor');

    if (btnAnchor) {

        const btnList = document.getElementById("button-fab-list");
        const upIcon = document.getElementById("up-icon");
        const downIcon = document.getElementById("down-icon");

        btnAnchor.addEventListener("click",  function(event) {
            if (event.target == btnAnchor) {
                btnList.classList.toggle('hidden');
                upIcon.classList.toggle('hidden');
                downIcon.classList.toggle('hidden');
            }
        });

    }

});

This works fine if I click on the button but not on the icon in the button. I have tried using z-index to place the button parent at z-50 and the icon as z-10 so the parent is stacked above the child.

What sis I miss / How do I set up the event to work on the button parent and all its children (i.e.: the icon)?

How do I access a constructor “this” variable? [duplicate]

In my updateCamera(event) function, I am trying to access this.camera as can be shown in my constructor. Unfortunately, it’s undefined in that function, I assume it’s a scope issue, but I’m not sure how to solve it. Any ideas? Thank you.

export default class Experience {
    constructor(options = {}) {
        this.camera = new Camera();
        // removed unnecessary stuff
        this.onMouseDrag();
    }

    updateCamera(event) {
        console.log(this.camera); //Prints "undefined" in the console
        this.camera.position.x = (event.clientX / window.innerWidth) * 2 - 1;
    }

    onMouseDrag() {
        window.addEventListener("mousedown", () => {
            window.addEventListener("mousemove", this.updateCamera);
        });
        window.addEventListener("mouseup", () => {
            window.removeEventListener("mousemove", this.updateCamera);
        });
    }

Javascript single quote inside string for exported text file [duplicate]

I am creating a node.js file that creates and readme file where the install directions need to be displayed as shell or javascript type font. However, I have not been able to use the single quotes required to make that work since they close out the string.

function generateExport(data) {
  const { username, ...title} = data;

  return `
    ```shell <--- how would you do this ?
    ${data.title} 
    ```  <----- and this?
`;
}

“Error : Cannot use ‘in’ operator to search for ‘length’ in [{“ID”:”2″,”Name”:”EAA2″}]” when performing $.each

What ever I do, I keep getting the same error. The only thing I have found that might of helped is the JSON.parse, but I still get the same problem. console log gives data as [{"ID":"2","Name":"EAA2"}]

I split it into two functions as I didn’t want to keep going back to the api everytime a user selects/de-selects an option.

I have also tried the following:

  1. Changing vars to lets
  2. Passing data.d from the update to the populate
function populateAvailableAuthorities() {
            var list = $('#availableAA');
            var data = JSON.parse($('#AAJSON').val());
            var auths = $('#tbSelectedAA').val();

            list.empty();
            
            $.each(data, function (key, entry) {
                if (!~auths.indexOf(entry.ID + ';')) {
                    list.append($('<option></option>').attr('value', entry.ID).text(entry.Name));
                }
            });
            
        }

        function updateListboxes() {
            var teams = '';
            let aa = $('#AAJSON');

            aa.empty();

            $('#cblTeams input:checked').each(function () {
                teams += $(this).attr('value') + ',';
            });

            if (teams.length > 1) {
                teams = teams.substr(0, teams.length - 1);

                $.ajax({
                    type: "POST",
                    url: '<%# ResolveUrl("~/api/Authorities.asmx/FetchByTeam") %>',
                    data: '{teams: "' + teams + '"}',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        aa.val(JSON.stringify(data.d));
                        populateAvailableAuthorities();
                    }
                });
            }
        }

Vue : How to use async await accordingly in a function array of which can have two functions for Promise.all?

I want to use await where I marked [here] in 1.vue. However, if I use await there then it emits error Unexpected reserved word 'await'. If I want to use async useFunctionToAllServers() sequentially after [Promise.all] then, where to put async or how to change async useFunctionToAllServers()? Or need to change submitToTheOthers()?

1.vue

<template>
  <div>
    <label for="imgUpload">
      <button class="point">upload</button>
    </label>
    <input
      type="file"
      class="input-file"
      ref="logo1"
      id="imgUpload"
      @change="sendFile('logo')"
    />
    <div v-if="imageData" class="imgBox">
      <img :src="imageData" />
    </div>

    <label for="imgUpload">
      <button class="point">upload1</button>
    </label>
    <input
      type="file"
      class="input-file"
      ref="logo1"
      id="imgUpload"
      @change="sendFile('logo1')"
    />
    <div v-if="imageData1" class="imgBox">
      <img :src="imageData1" />
    </div>
    <button @click="useFunctionToAllServers">BUTTON</button>
  </div>
</template>
<script>
import {
  updateGeneralInfo,
  createUploadToOther,
  updateGeneralInfoToOther,
} from '@/2'

export default {
  data() {
    return {
      filename: '',
      filename1: '',
      originalFilename: '',
      originalFilename1: '',
      imageData: '',
      imageData1: '',
      serverNames: ['a server', 'b server'],
      idxs: [0, 1],
      serverFullAddress:['http://a.url', 'http://b.url'],
      serverResCheck:[],
      isLogoChanged:false,
      isLogo1Changed:false,
    }
  },
  methods: {  
    sendFile(type) {
      let file = ''
      if (type == 'logo') {
        file = this.$refs.logo.files[0]
      } else {
        file = this.$refs.logo1.files[0]
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        if (type == 'logo') {
        this.imageData = e.target.result
        } else {
        this.imageData1 = e.target.result
        }
      }
    },
    sendFileToOther(type, serverFullURL) {
      let file = ''
      if (type == 'logo') {
        file = this.$refs.logo.files[0]
        this.originalFilename = this.$refs.logo.files[0].name
      } else {
        file = this.$refs.logo1.files[0]
        this.originalFilename1 = this.$refs.logo1.files[0].name
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      const formdata = new FormData()
      formdata.append('logo', file)
      
      formdata.append('serverURL', serverFullURL)

      return createUploadToOther(formdata)
    },
    
    async useFunctionToAllServers() {
      
        let data = {
          foo: this.foo,
          bar: this.bar,
        }
        
        await updateGeneralInfo(data).then().catch()
      
        await Promise.all(this.submitToTheOthers()).catch((err) =>{ // [Promise.all]
          console.log('Promise.all err>>', err)
        });  
        
        let notWorkingServers = []
        for(let i=0; i< this.idxs.length ; i++){
          if(!this.serverResCheck[i]){
          notWorkingServers.push(this.serverNames[i])
          }
        }
        if(Array.isArray(notWorkingServers) && notWorkingServers.length == 0){
          alert('not working : ', notWorkingServers)
        }else{
          alert('all server works')
        }      
    },
    submitToTheOthers(){
      let data = {
        foo: this.foo,
        bar: this.bar,
      }
      let logoData ={}
      if(this.originalFilename){
        data.logo = this.originalFilename
        logoData.logo = true
      }else if(this.isLogoChanged){
        data.logo = this.logo
      }
      if(this.originalFilename1){
        data.logo1 = this.originalFilename1
        logoData.logo1 = true
      }else if(this.isLogo1Changed){
        data.logo1 = this.logo1
      }
      
      return this.idxs.map( (_entry, i) => {
        return updateGeneralInfoToOther(1, data, this.serverFullAddress[i]).then((res) => { // [here2]
          if (res.status == 200) {
            this.serverResCheck[i] = true
            if(logoData.logo){
              this.sendFileToOther('logo', this.serverFullAddress[i]).then((res) => { // [here]
              }).catch((err) => {
                this.serverResCheck[i] = false
              })
            }
            if(logoData.logo1){
              this.sendFileToOther('logo1', this.serverFullAddress[i]).then((res) =>{ // [here]
              }).catch((err) => {
                this.serverResCheck[i] = false
              })
            }
          }else{
            this.serverResCheck[i] = false            
          }
        }).catch((err) => {
          this.serverResCheck[i] = false
        })
      })
    },
  },
}
</script>

2.js

import axios from 'axios'
export const headers = {
  'Content-Type': 'application/json',
  'header1' : 'header1',
  'header2' : 'header2',
}

export function updateGeneralInfoToOther(id, data, serverAddress) {
  data.serverAddress = serverAddress
  return axios.put(`/u/r/l/${id}`, data, { headers })
}

export function updateGeneralInfo(id, data) {
  return axios.put(`/extra/u/r/l/${id}`, data, { headers })
}

export function createUploadToOther(data) {
  return axios.post('/u/r/l', data, { headers })
}

How to validate a Cloned form fields by javascript?

// Cloning Form
  var id_count = 1;
  $('.add').on('click', function() {
    var source = $('.form-holder:first'), clone = source.clone();
    clone.find(':input').val("").attr('name', function(i, val) {
      return val + '-'+id_count;
    });

    clone.appendTo('.form-holder-append');
      id_count++;

  });

  // Removing Form Field
  $('body').on('click', '.remove', function() {
    var closest = $(this).closest('.form-holder').remove();
  });
.remove
{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-folder">

 <input type="file" name="variant_images" id="upload_file" required multiple>
  
 
  
  <button class="remove">remove -</button>
</div>



  <div class="form-holder-append"></div><br>
  <button class="add">Add +</butoon>
  
// Cloning Form
  var id_count = 1;
  $('.add').on('click', function() {
    var source = $('.form-holder:first'), clone = source.clone();
    clone.find(':input').val("").attr('name', function(i, val) {
      return val + '-'+id_count;
    });

    clone.appendTo('.form-holder-append');
      id_count++;

  });

  // Removing Form Field
  $('body').on('click', '.remove', function() {
    var closest = $(this).closest('.form-holder').remove();
  });





//Image upload restriction
$(document).ready(function(){
  $('#upload_file').change(function(){
   //get the input and the file list
    var images = document.getElementById('upload_file');
      if(images.files.length<4){
          alert ("Please Upload minimum 4 images.");
          $("#upload_file").val('');

      }
   });
});
.remove
{
display:none;
}
.form-holder-append .remove {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-holder">

  <input type="file" name="variant_images" id="upload_file" required multiple>
 <button class="remove">remove - </button>

</div>
<div class="form-holder-append"></div><br>
<button class="add">add + </button>

I want to validate a each cloned forms input file, the validation is –>minimum 4 images should be uploaded otherwise the field returns empty value. But I have got this for fist form. After cloned, the id would be same and this is not working. How to write this for unlimited clone forms?