Adding a new Media Stream in mid of a call in WebRTC (peerjs)

I am making a WebRTC video call application using peerjs library and every peer can chose what stream to start the call with, so I have two streams audio and video stream:

const peer = new Peer()
let remotePeerConnection = null
let audioStream;
let videoStream;
try{
    audioStream = await navigator.mediaDevices.getUserMedia({audio:true})
}
catch(err){
    audioStream = null;
}
try{
    videoStream = await navigator.mediaDevices.getUserMedia({video:true})
}
catch(err){
    videoStream = null;
}

And then I mix them together

let mixedStream = new MediaStream()
if(audioStream){
   mixedStream.addTrack(audioStream.getAudioTracks()[0])
}
if(videoStream){
   mixedStream.addTrack(videoStream.getVideoTracks()[0])
}
const myVideo = document.getElementById("my-video")
myVideo.srcObject = mixedStream
myVideo.play()

and I have a call function to call other peer with the mixed stream which can be only video stream or only audio stream or both,

const call = (peerID) => {
    const call = peer.call(peerID,mixedStream)
    remotePeerConnection = call.peerConnection
    call.on("stream",remoteStream=>{
        const remoteVideo = document.getElementById("remote-video")
        remoteVideo .srcObject = remoteStream
        remoteVideo .play()
    })
}

the question is if I want to start the call with only audio stream so the mixed stream only has an audio tracks added at the beginning, and then if I want to add video stream to the call How could I do that , to be more clear not replacing an existing stream which I already know, Which kinda looks like this example :

// assume videoTrack is come from what ever
const sender = remotePeerConnection.getSenders().find(s=>s.track.kind === "video")
if(sender){
   sender.replaceTrack(videoTrack)
}

I tried adding the video track using addTrack method on the remotePeerConnection

try{
    videoStream = await navigator.mediaDevices.getDisplayMedia({video:true})
}
catch(err){
   console.log(err)
}
if(videoStream){
    const videoTrack = videoStream.getVideoTracks()[0]
    remotePeerConnection.addTrack(videoTrack)
}

but it does not seem to work, how could I do that without closing the call and re-call with a new mixed stream.

How to properly use formatting with chartjs?

I am trying to use formatting in Chart.js. I’ve configured the imports correctly, but it still doesn’t display what I want

It doesn’t work on my local pc. I uploaded the same code to codepen and it didn’t work either. You can verify it here

var donutEl = document.getElementById("donut").getContext("2d");
var data = [4, 9, 5, 2];

var pieChart = new Chart(donutEl, {
type: 'doughnut',
data: {
    datasets: [
        {
            data: [10, 20, 15, 5, 50],
            backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
        },
    ],
    labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
},
options: {
    plugins: {
        datalabels: {
            formatter: (value) => {
                return value + '%';
            }
        }
    }
}
})

Any ideas what am I doing wrong? Thanks

Reference a key which is `undefined` in JavaScript

I have implemented a map which allocate a gigantic list of IPs in an efficient memory/search manner. It goes like this:

function pushToBucket(bucket, ip) {
    const intIp = ip.split('.').map(Number)
    var part1, part2, part3, part4
    ;[part1, part2, part3, part4] = intIp

    if (!bucket[part1]) bucket[part1] = {}
    if (!bucket[part1][part2]) bucket[part1][part2] = {}
    if (!bucket[part1][part2][part3]) bucket[part1][part2][part3] = []
    if (bucket[part1][part2][part3].indexOf(part4) < 0) bucket[part1][part2][part3].push(part4)
}

with regular IPs v4 like this:
ips = ["100.1.108.246", "101.0.80.218", "101.108.122.200"]

I feel like there should be a better way in referencing possible nested values in the bucket. Is there a way to avoid repetitions like: In an imaginary implementation (very possible in symbolic languages), we would declare something similar to:

function pushToBucket(bucket, ip) {
    const intIp = ip.split('.').map(Number)
    var part1, part2, part3, part4
    ;[part1, part2, part3, part4] = intIp
    deep1 = bucket[part1]
    deep2 = deep1[part2]
    deep3 = deep2[part3]
    deep4 = deep3.indexOf(part4) < 0

    if (!deep1) deep1 = {}
    if (!deep2) deep2 = {}
    if (!deep3) deep3 = []
    if (deep4) deep4.push(part4)
}

note: first algorithm works and is efficient, so this question is about a better design, either in vanilla JS or using some library or even a data-structure.

Listening to multiple events that emit data

I have a code that triggers the fire() function only after both events happen. Only one of the events (event a) emit data that i want to work with, but when the event without data (event b) fires first, the data stays “null”.

let got = { “first”: false, “second” : false }
function fire(event, data=null)
{
got[ event ];
if ( got.first, got.second ) {
   console.log(data);
   got = { “first”: false, “second”: false }
   }
}

eventEmiter.on(“a” (data) => {
   fire(“first”, data)
})

eventEmitter.on(“b” () => {
   fire(“second”)
})

logs data:

eventEmitter.emit(“a”, data);

eventEmitter.emit(“b”);

logs null:

eventEmitter.emit(“b”);

eventEmitter.emit(“a”, data);

My question is, how can i make it so that it always logs the data no matter the order in which the events fire? I couldnt come up with any solution that worked, any help is appreciated!

PS: i wrote the code out of memory, sorry if the code above has some mistakes, just pretend it works

what is the correct way to collect input data WITHOUT LAG on typing in REACT?

so it’s been a month i’m working with react.

there is a problem i didn’t know what to do with it.

in onChange event handlers EVEN in the smallest page and project there is a delay in typing and specially Delay in Removing text.

why is this happenig ?
i mean react is popular because of Fast UI right? so what we should do to handle Forms without this Perfomance Problem ?

why there is a lag in this form ?

const LoginForm = () => {
  // State & Validate Schema
  const formik = useFormik({
    initialValues: {
      email: "",
      password: "",
      rememberMe: false,
    },
    validationSchema: Yup.object({
     blah blah some validation
    }),
    onSubmit: (value) => {
       console.log(value, "Submitted");
    },
  });

  return (
    <>
      <Container maxWidth="sm" disableGutters>
        <Box>
          <h3>Log to the Account</h3>
          <form onSubmit={formik.handleSubmit}>
                <TextField
                error={formik.touched.email && formik.errors.email !== undefined}
                name='email'
                label='Email'
                value={formik.values.name}
                onBlur={formik.handleBlur} // If Input is Touched Show Error
                onChange={formik.handleChange}
                helperText={formik.touched.email && formik.errors.email}
                autoComplete="on"
                              />
                <TextField
                error={formik.touched.password && formik.errors.password!== undefined}
                name='password'
                label='Password'
                value={formik.values.password}
                onBlur={formik.handleBlur}
                onChange={formik.handleChange}
                helperText={formik.touched.password&& formik.errors.password}
                autoComplete="on"
                              />
                  <Button type="submit" variant="contained" size="medium">
                    Login
                  </Button>
                  <span>Remember Me</span>
                  <Checkbox
                    value={formik.values.rememberMe}
                    name="rememberMe"
                    onChange={formik.handleChange}
                  />
          </form>
        </Box>
      </Container>
    </>
  );
};

Controller List always is null from view using Html.BeginForm() ASP.NET MVC

I want to get multiple instances of my model objects sent to the controller as a list but for some reason, the count of the list is always 1 and the value of the object is always 0 so nothing is actually posted when submit is pressed.

This is my View:

@model List<MVCModel.Models.Student>

 <b>Items</b>    @ViewBag.Items <br />
 <b>Value</b>    @ViewBag.Value <br />
  
@using (Html.BeginForm("Form", "Home", FormMethod.Post))
{
<table>
    <tbody id="GenaratorList">
        <tr>
          @{
            int counter = 0;
            <td>Enter Name: </td>
            <td>@Html.TextBoxFor(m => m[counter].Name, new {id = "Name"})</td>
            <td>Enter Age: </td>
            <td>@Html.TextBoxFor(m => m[counter].Age, new {id = "Age"})</td>
            <td><input type="button" value="Add" onclick="addGenarator()" /></td>
        </tr>
        counter++;
        }
     <tbody>
</table>
<input type="submit" value="Submit Form"/>
}

<script>
    count = 0;
    function addGenarator() {
        var Name = $('#Name').val();
        var Age = $('#Age').val();
        var Student = "studentModels[" + count + "]";
        $('#GenaratorList').append('<tr><td><input id="' + Student + '.Name" Name="' + Student + '.Name" type="text" class="form-control" readonly value="' + Name + '"></td><td><input id="' + Student + '.Age" Age="' + Student + '.Age" type="text" class="form-control" readonly value="' + Age + '"></td></tr>');
        $('#Name,#Age').val('');
        count++;
    }
</script>

This is my Controller:

[HttpPost]
        public ActionResult Form(List<Student> s)
        {
            ViewBag.Items = s.Count; // ALWAYS RETURNS 1
            ViewBad.Value = s[0].Age // TEST VALUE OF FIRST ITEM RETURNS 0
            return View("Index");
        }

This is my model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCModel.Models
{
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

useEffect hook to filter through the JSON data and spit out new URL params to filter jobs (API)

I am very close to finishing it but something does not click. I pass the async data from another function to useEffect, filter it through switch + .filter and spit it out to UrlParams to be displayed but it does not filter the jobs that are displayed but only changes the URL (example: http://localhost:3001/jobs=null&location=null&since=null&conditions=remote/hybrid). (also after I change URL params it returns an empty array)

If possible can you please add an explanation for me to understand what I was doing wrong with some examples, would be great to learn that way! I will include all the code components here (useState, useEffect, fetch/filter function + jsx)

//useState
        const [jobCondition, setJobConditionFilter] = useState('On-site/Remote');

//function + useEffect
        const getJobsLocation = useCallback(async (filterCondition) => {
        const jobs = await getJobs();
        const response = jobs.data.nodes;
        const conditionOptions = {
          'On-site': 'in_person',
          Remote: 'remote',
          Hybrid: 'hybrid',
        };
    
        const filteredJobs = await response.filter(
          (job) => job.jobFilter === conditionOptions[filterCondition],
        );
    
        if (!filteredJobs) {
          return {};
        }
        return filteredJobs;
      }, []);

  useEffect(() => {
    getJobsLocation(jobCondition).then((jobs) => {
      let condition = jobs;
      console.log(condition);
      console.log('this is condition log');
      switch (jobCondition) {
        case 'On-site': condition.filter((con) => con.jobLocation === 'in_person');
          break;
        case 'Remote': condition.filter((con) => con.jobLocation === 'remote');
          break;
        case 'Hybrid': condition.filter((con) => con.jobLocation === 'hybrid');
          break;
        default:
          condition = null;
      }
      if (condition != null) {
        const params = new URLSearchParams({
          jobs: jobFilter || null,
          location: locationFilter || null,
          since: datePosted || null,
          conditions: jobCondition,
        });
        history.push({ pathname: '/', search: `${params.toString()}` });
        console.log(condition);
        console.log('this is condition afterlog');
        return;
      }
      const params = new URLSearchParams({
        jobs: jobFilter || null,
        location: locationFilter || null,
        since: null,
        conditions: null,
      });
      history.push({ pathname: '/', search: `${params.toString()}` });
    });
  }, [jobCondition, getJobsLocation]);


//JSX
      <CustomAutocomplete
        sx={{
          width: '300px',
          marginLeft: '5px',
          marginTop: '10px',
        }}
        placeholder="Location"
        value={jobCondition}
        setValue={setJobConditionFilter}
        options={jobConditionFilter}
        endAdornmentIcon={(
          <div style={{ marginRight: '15px', marginTop: '-10px' }}>
            <ArrowDropDownIcon fontSize="10px" />
          </div>
        )}
      />

i am sending get request from postman , getting can not read the properties of undefined full name

when I remove the full name from item.createdBy.fullname its show the whole data but if I only want to access the full name from data its give error ‘can not read the properties of undefined fullname’

data=data.map(function(item){

          return {
            tagName:item.tagName,
             createdBy:item.createdBy.fullName,
             createdOn:item.createdAt,
             status:item.isActive,
          }
          
        })

React inputs stuck and not changing [duplicate]

In my project I have a ticket system where the price, the number of tickets and the totals are supposed to update. I called a function with use effect to get the initial values set when the component is first loaded and that all works fine. The problem I have is that I am not able to change anything that is set to true the set_init_val function.

const Bookings = (state) => {
  /*Constants for ticket pricing*/
  const kingston_adult_ticket_cost = 180;
  const portland_adult_ticket_cost = 200;
  const negril_adult_ticket_cost = 280;
  const ochorios_adult_ticket_cost = 240;
  const montegobay_adult_ticket_cost = 260;

  /*Initialize variables with initial state*/
  const [fname, setFname] = useState("");
  const [lname, setLname] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [adultText, setAdultText] = useState("Adult");
  const [adultTotal, setAdultTotal] = useState(0);
  const [childText, setChildText] = useState("Child");
  const [childTotal, setChildTotal] = useState(0);
  const [total, setTotal] = useState(0);
  const [adult_tickets, setAdultTickets] = useState(0);
  const [children_tickets, setChildrenTickets] = useState(0);
  const [kingston, setKingston] = useState(false);
  const [portland, setPortland] = useState(false);
  const [negril, setNegril] = useState(false);
  const [ochorios, setOchorios] = useState(false);
  const [montegobay, setMontegobay] = useState(false);

  /*get information sent through artificial URL*/
  let location = useLocation();

  /*Set initial values*/
  function set_init_val() {
    /* counter for the total amount of adult tickets */
    var adultTotal_c = 0;

    /*Set checkboxes based on what is sent over*/
    if (location.state != null) {
      if (
        location.state.destination_s === "kingston" ||
        location.state.destination_s === "all"
      ) {
        setKingston(true);
        adultTotal_c = adultTotal_c + kingston_adult_ticket_cost;
      }

      if (
        location.state.destination_s === "portland" ||
        location.state.destination_s === "all"
      ) {
        setPortland(true);
        adultTotal_c = adultTotal_c + portland_adult_ticket_cost;
      }

      if (
        location.state.destination_s === "negril" ||
        location.state.destination_s === "all"
      ) {
        setNegril(true);
        adultTotal_c = adultTotal_c + negril_adult_ticket_cost;
      }

      if (
        location.state.destination_s === "ochorios" ||
        location.state.destination_s === "all"
      ) {
        setOchorios(true);
        adultTotal_c = adultTotal_c + ochorios_adult_ticket_cost;
      }

      if (
        location.state.destination_s === "montegobay" ||
        location.state.destination_s === "all"
      ) {
        setMontegobay(true);
        adultTotal_c = adultTotal_c + montegobay_adult_ticket_cost;
      }

      setAdultTickets(location.state.adult_s);
      setChildrenTickets(location.state.child_s);

      adultTotal_c = adult_tickets * adultTotal_c;
      setAdultTotal(adultTotal_c);

      var childTotal = (children_tickets * (adultTotal / adult_tickets)) / 2;
      setChildTotal(childTotal);

      var total_c = adultTotal + childTotal;
      setTotal(total_c);
    } else {
      return;
    }
  }

  const handleCheck = () => {
    setMontegobay(!montegobay);
  };

  useEffect(() => {
    set_init_val();
  });

  return (
    <>
      <Header />
      <Container>
        <h1 className="booking_title">Book Your Next Adventure</h1>
        <Form>
          <Row>
            <Col style={{ padding: "50px" }}>
              <h1 className="formheader">Booking Information</h1>
              <div style={{ padding: "15px" }}>
                <Form.Group className={"mb-3"} style={{ fontWeight: "bold" }}>
                  <Form.Label>First Name</Form.Label>
                  <Form.Control
                    placeholder={"First name"}
                    style={{ width: "500px" }}
                  />
                </Form.Group>

                <Form.Group className={"mb-3"} style={{ fontWeight: "bold" }}>
                  <Form.Label>Last Name</Form.Label>
                  <Form.Control
                    placeholder={"Last name"}
                    style={{ width: "500px" }}
                  />
                </Form.Group>

                <Form.Group className={"mb-3"} style={{ fontWeight: "bold" }}>
                  <Form.Label>Phone</Form.Label>
                  <Form.Control
                    name={"phone"}
                    placeholder={"000-000-0000"}
                    style={{ width: "500px" }}
                  />
                </Form.Group>

                <Form.Group className={"mb-3"} style={{ fontWeight: "bold" }}>
                  <Form.Label>Email</Form.Label>
                  <Form.Control
                    placeholder={"[email protected]"}
                    style={{ width: "500px" }}
                  />
                </Form.Group>

                <Form.Label style={{ fontWeight: "bold" }}>
                  Destinations
                </Form.Label>
                {["checkbox"].map((type) => (
                  <div key={`default-${type}`} className="mb-3">
                    <Form.Check
                      type={type}
                      id={`default-${type}`}
                      label={`Kingston $180`}
                      checked={kingston}
                      onChange={() =>
                        kingston ? setKingston(false) : setKingston(true)
                      }
                    />

                    <Form.Check
                      type={type}
                      id={`default-${type}`}
                      label={`Portland $200`}
                      checked={portland}
                      onChange={() =>
                        portland ? setPortland(false) : setPortland(true)
                      }
                    />

                    <Form.Check
                      type={type}
                      id={`default-${type}`}
                      label={`Negril $280`}
                      checked={negril}
                      onChange={() =>
                        negril ? setNegril(false) : setNegril(true)
                      }
                    />

                    <Form.Check
                      type={type}
                      id={`default-${type}`}
                      label={`Ocho Rios $240`}
                      checked={ochorios}
                      onChange={() =>
                        ochorios ? setOchorios(false) : setOchorios(true)
                      }
                    />

                    <Form.Check
                      type={type}
                      id={`default-${type}`}
                      label={`Montego Bay $260`}
                      checked={montegobay}
                      onChange={handleCheck}
                    />
                  </div>
                ))}
                <Row>
                  <Col>
                    <Form.Label style={{ fontWeight: "bold" }}>
                      Adult
                    </Form.Label>
                    <Form.Select value={adult_tickets}>
                      <option>0</option>
                      <option>1</option>
                      <option>2</option>
                      <option>3</option>
                      <option>4</option>
                      <option>5</option>
                      <option>6</option>
                    </Form.Select>
                  </Col>

                  <Col>
                    <Form.Label style={{ fontWeight: "bold" }}>
                      Children
                    </Form.Label>
                    <Form.Select value={children_tickets}>
                      <option>0</option>
                      <option>1</option>
                      <option>2</option>
                      <option>3</option>
                      <option>4</option>
                      <option>5</option>
                      <option>6</option>
                    </Form.Select>
                  </Col>

                  <Col>
                    <Form.Label style={{ fontWeight: "bold" }}>Date</Form.Label>
                    <Form.Control type={"date"} />
                  </Col>
                </Row>
              </div>
            </Col>

            <Col className={"paycol"} style={{ padding: "50px" }}>
              <h1 className="formheader">Payment Information</h1>

              <div className={"totals"} style={{ padding: "15px" }}>
                <Row>
                  <Col>{adultText}</Col>
                  <Col>${adultTotal}</Col>
                </Row>

                <Row>
                  <Col>{childText}</Col>
                  <Col>${childTotal}</Col>
                </Row>

                <Row>
                  <Col>Total</Col>
                  <Col>${total}</Col>
                </Row>
              </div>

              <div style={{ marginTop: "50px" }}>
                <Form.Label style={{ fontWeight: "bold" }}>
                  Credit/Debit Card number
                </Form.Label>
                <Form.Control placeholder={"0000 0000 0000 0000"} />

                <Row style={{ marginTop: "50px" }}>
                  <Col>
                    <Form.Label style={{ fontWeight: "bold" }}>
                      Exp month
                    </Form.Label>
                    <Form.Select>
                      <option value="01">01</option>
                      <option value="02">02</option>
                      <option value="03">03</option>
                      <option value="04">04</option>
                      <option value="05">05</option>
                      <option value="06">06</option>
                      <option value="07">07</option>
                      <option value="08">08</option>
                      <option value="09">09</option>
                      <option value="10">10</option>
                      <option value="11">11</option>
                      <option value="12">12</option>
                    </Form.Select>
                  </Col>

                  <Col>
                    <Form.Label style={{ fontWeight: "bold" }}>
                      Exp Year
                    </Form.Label>
                    <Form.Select>
                      <option value="2022">2022</option>
                      <option value="2023">2023</option>
                      <option value="2024">2024</option>
                      <option value="2025">2025</option>
                      <option value="2026">2026</option>
                      <option value="2027">2027</option>
                      <option value="2028">2028</option>
                      <option value="2029">2029</option>
                      <option value="2030">2030</option>
                      <option value="2031">2031</option>
                      <option value="2032">2032</option>
                    </Form.Select>
                  </Col>

                  <Col>
                    <Form.Label style={{ fontWeight: "bold" }}>CVC</Form.Label>
                    <Form.Control placeholder={"000"} />
                  </Col>
                </Row>
              </div>

              <br />
              <br />
              <div className="checkbox pcheck">
                <label htmlFor="destinations-1">
                  <input type="checkbox" id="cash" onClick="toggle()" />
                  <b>&nbsp; Pay with with cash</b> <br />
                  <br />
                  <h3>
                    By paying with cash I agree to advise my tour guide 30
                    minutes ahead of time that I need to complete payment
                  </h3>
                </label>
              </div>
            </Col>
          </Row>
        </Form>
      </Container>
      <Footer />
    </>
  );
};

export default Bookings;

Why can’t Polygon appear in react-leaflet from API?

I need to access Polygon coordinates from API. I’m using Leaflet and React-Leaflet but it’s not showing up on maps. This is my Polygon component:

import React, { useEffect, useState, useRef } from "react";
import { GeoJSON } from "react-leaflet";
import { getHome } from "../arcgis";
import { useRecoilValue, useSetRecoilState } from "recoil";
import { arcgisToken } from "../../../recoil";
import { mapBounds, loadingMap } from "../state";

export default function Home(props) {
    const [data, setData] = useState();
    const setIsLoading = useSetRecoilState(loadingMap);
    const bounds = useRecoilValue(mapBounds);
    const tokenArcgis = useRecoilValue(arcgisToken);
    const geoJsonLayer = useRef(null);

    useEffect(() => {
        const fetchDataSpeedtestKel = () => {
            const body = {
                f: "json",
                where: `1=1`,
                outFields: "*",
                returnGeometry: true,
                rollbackOnFailure: true,
                geometry: JSON.stringify({
                    xmin: bounds.west,
                    ymin: bounds.south,
                    xmax: bounds.east,
                    ymax: bounds.north,
                    spatialReference: { wkid: 4326 },
                }),
                geometryType: "esriGeometryEnvelope",
                inSR: 4326,
                outSR: 4326,
                resultRecordCount: 2000,
                token: tokenArcgis,
            };

            setIsLoading(true);
            getApartmentAPC(body)
                .then((response) => {
                    const array = [];
                    response.features.forEach((element) => {
                        array.push({
                            type: "Feature",
                            properties: element["attributes"],
                            geometry: {
                                type: "Polygon",
                                coordinates: [
                                    element["geometry"]["x"],
                                    element["geometry"]["y"],
                                ],
                            },
                        });
                    });

                    const FeatureCollection = {
                        type: "FeatureCollection",
                        features: array,
                    };
                    if (geoJsonLayer.current) {
                        geoJsonLayer.current.clearLayers().addData(FeatureCollection);
                    }
                    setData(FeatureCollection);
                })
                .catch((err) => console.log(err))
                .finally(() => setIsLoading(false));
        };

        fetchDataSpeedtestKel();
    }, [bounds, setIsLoading, tokenArcgis]);

    if (data) {
        return (
            <>
                <GeoJSON
                    ref={geoJsonLayer}
                    data={props.data}
                />
            </>
        );
    } else {
        return <div></div>;
    }
}

The import { get Home } from "../arcgis"; section to fetch data or Polygons from the API.

And I took from the API and the link from the postman app:

import { instanceArcgis } from "./instance";
import { FormDataCustom } from "../utils/baseFunctions";

export const getHome = async (params) => {
  try {
    const body = FormDataCustom(params);
    const result = await instanceArcgis.post(
      "/rest/services/tracking/Home/1/query",
      body,
    );

    return await result?.data;
  } 
};

The following image shows Polygon data not appearing in the Home feature on maps from the API:
enter image description here

Firebase realtime database trouble with next.js

The problem is with the Id variable. If i change the variable to a string ex “hello” it writes to the database fine. Also when I use the string instead of the variable, I have to return an error first before the database starts working ex I add () to the linkUserName save then take them away save again and my code works.

import React, { useState } from "react";
import {initializeApp} from 'firebase/app';
import { getDatabase, ref, set, } from 'firebase/database';

export default function Username(props) {
        const [userName, setUsername] = useState('');
        const [Id, setId] = useState('')
        // var d = new Date().getTime();
        const clientCredentials = {
            apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
            authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
            databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
            projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
            storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
            messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
            appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
        }
        const app = initializeApp(clientCredentials);
        const address = props.address;
        const db = getDatabase();

        function writeUserData(userId, userN, address) {
            const reference = ref(db, 'users/' + userId);

            set(reference, {
                username: userN,
                walletAddress: address
            });
        }

        function handleChange(event) {
            setUsername(event.target.value);
        }

        function linkUserName() {
            setId(new Date().getTime());
            writeUserData( { Id }, { userName }, { address });
            console.log('success')
        }

        return (
            <>
                <div>
                    <p className = "account-Info" >address: {address}</p>
                </div>
                <div id="form">
                    <h2 className='user-Create' > Create Username</h2>
                    <form id='set-User'>
                    <input id='username' className="user-Create" type='text' onChange={ handleChange } 
                    required minLength='3' maxlength='30' pattern="[a-zA-Z0-9_]+" title='only letters, numbers, and underscores.'/>
                        <button className='user-Create' type="submit" onClick={ linkUserName }>Link Username</button>
                        <p id='call-User' className='account-Info'> { userName }</p>                    
                    </form>
                </div>
            </>
        );
}

How does answer of this javascript mcq code is 10 -10? [duplicate]

function changeValue(param) {
Param =5;
}
Let a =10;
Let b =5;
changeValue(b);
Const result = a+ " - "+ b;

What is the value of result when code executes?
A. 5 – 10
B. 10 -10
C. 5 -5
D. 10 – 5
Answer: B

I came across this Javascript MCQ whose answer is B. 10 -10.
But I a unable to understand why? As per my knowledge answer should be D. 10 – 5.

I may be unaware of something around this question. It would be helpful if I get know the reasoning behind this answer B.

Angular, mouseover speed is choppy?

I’m trying to create a “tooltip” that follows the mouse around and disappears when it leaves it’s location. However, the tooltip created is slow, it doesn’t follow my mouse around smoothly and seems choppy. How do I fix this?

https://stackblitz.com/edit/angular-l2wgqt?file=src/app/app.component.ts

TS:

export class AppComponent {
  name = 'Angular';

  constructor(private el: ElementRef) {}

  first(e: { pageX: any; pageY: any }) {
    console.log(e.pageX, e.pageY);

    this.el.nativeElement.querySelector('#first').style.left =
      e.pageX.toString() + 'px';
    this.el.nativeElement.querySelector('#first').style.top =
      e.pageY.toString() + 'px';
    this.el.nativeElement.querySelector('#first').classList.add('show');
  }

  second(e: { pageX: any; pageY: any }) {
    this.el.nativeElement.querySelector('#first').style.left = '0px';
    this.el.nativeElement.querySelector('#first').style.top = '0px';

    this.el.nativeElement.querySelector('#first').classList.remove('show');
  }
}

HTML:

<div (mouseover)="first($event)" (mouseleave)="second($event)"class="place-welcome">
<h2>This is a Panel</h2>
<p>Hello my darling</p>
</div>

<div id="first">asdasdasdasd</div>

How to hide border in react-chart-js-2

I am facing a rather troublesome problem with chart as follows:

  • I want to remove the outermost border and keep the inner lines, but the chart doesn’t allow me to do that. I tried using ‘drawBorder: false’, but it still doesn’t work. Is there any way to handle this?
  • How to remove the value of the origin x-Axis and Y-Axis?
    please refer to the image
  • How to edit the value of A-Xis? I want it to increase by 1000 each time on the X-Axis.

image