Category: javascript
Category Added in a WPeMatico Campaign
Loop through an array of strings and render it as a Prop in a Component in React
Questions similar to this were either irrelevant or complicated. I’ve referred to this SO thread but still not getting my desired output.
Desired output:
Hi there, Anna!
Hi there, Je!
Hi there, Ram!
I’ve tried playing around with .map() but only resulted in no output.
Here is the code I’ve written:
import React from 'react';
import ReactDOM from 'react-dom';
class Greeting extends React.Component {
render() {
return <h1>Hi there, {this.props.firstName}!</h1>;
}
}
const names = ["Anna", "Je", "Ram"];
const greet_em = names.map(name => (<Greeting firstName={name}/>));
ReactDOM.render(
{greet_em},
document.getElementById('app')
);
download file and set file as downloaded at same time
I’m using Vue and have an application that uses a template file. This file can be updated and I’d like to keep state in the user session store of if they have downloaded a new copy of the file.
I can easily call a backend api to toggle this on a button click.
How would I wire up the button to download the file (same behavior as an a href) but also call the back end api to toggle the hasSeen variable in session store.
How can I redirect the user from one page?
How can I redirect the user from one page to another using jQuery or pure JavaScript?
How can i replace string in react
im using emoji api and i get emoji unicode’s like this U+1F425 to be able to show emoji’s in jsx. i have to replace U+1F425 to u{1F425} . basically i just need to get 1F425 from the api.
Emoji.jsx
import React, { useEffect, useState } from "react";
import Sidebar from "../../Sidebar/Sidebar";
import "./Emoji.css";
const Emoji = ({ isAuth, setIsAuth }) => {
const [type, setType] = useState([]);
const getEmoji = () => {
fetch("https://emojihub.herokuapp.com/api/all/group_animal_bird")
.then((resp) => resp.json())
.then((dat) => (console.log(dat), setType(dat)));
};
useEffect(() => {
getEmoji();
console.log(type);
}, []);
return (
<>
{type.map((emo) => (
<>
<h6>{emo.name}</h6>
<span>{emo.unicode}</span> // This Not
<span>{"u{1F985}"}</span> //This works
</>
))}
</>
);
};
export default Emoji;
thanks for your help!
WebRTC Stream Is Not Showing On Client Side
i’m new here and i started learning java script like 2 weeks ago.
i’m trying to build a video conference private website and the problem is :
video stream is showing on user A and User B but they cant see each others’ stream
here is the javascript app code
var AppProcess = (function(){
var peers_connection_ids = [];
var peers_connection = [];
var remote_vid_stream = [];
var remote_aud_stream = [];
var videoCamTrack;
var local_div;
var serverProcess;
var audio;
var isAudioMute = true;
var rtp_aud_senders = [];
var video_state = {
None:0,
Camera: 1,
ScreenShare:2,
};
var video_st = video_state.None;
var rtp_vid_senders = [];
async function _init(SDP_function, my_connid){
serverProcess = SDP_function;
my_connection_id = my_connid;
eventProcess();
local_div = document.getElementById("locaVideoPlayer");
}
function eventProcess(){
$("#micMuteUnmute").on("click", async function(){
if(!audio){
await loadAudio();
}
if(!audio){
alert("Audio Permission Is Not Granted");
return;
}
if(isAudioMute){
audio.enabled = true;
$(this).html("<span class='material-icons'>mic</span>");
updateMediaSenders(audio, rtp_aud_senders);
}else{
audio.enabled = false;
$(this).html("<span class='material-icons'>mic_off</span>");
removeMediaSenders(rtp_aud_senders);
}
isAudioMute = !isAudioMute;
});
$("#videoCamOnOff").on("click", async function(){
if(video_st == video_state.Camera){
await videoProcess(video_state.None);
}else{
await videoProcess(video_state.Camera);
}
});
$("#btnScreenShareOnOff").on("click", async function(){
if(video_st == video_state.ScreenShare){
await videoProcess(video_state.None);
}else{
await videoProcess(video_state.ScreenShare);
}
});
}
async function videoProcess(newVideoState){
if(newVideoState == video_state.None){
$("videoCamOnOff").html("<span class='material-icons'>videocam_off</span>");
}
if(newVideoState == video_state.Camera){
$("videoCamOnOff").html("<span class='material-icons'>videocam_on</span>");
}
try{
var vstream = null;
if(newVideoState == video_state.Camera){
vstream = await navigator.mediaDevices.getUserMedia({
video:{
width:1920,
height:1080,
},
audio:false,
});
}else if(newVideoState == video_state.ScreenShare){
vstream = await navigator.mediaDevices.getDisplayMedia({
video:{
width:1920,
height:1080,
},
audio:false,
});
}
if(vstream && vstream.getVideoTracks().length > 0){
videoCamTrack = vstream.getVideoTracks()[0];
if(videoCamTrack){
local_div.srcObject = new MediaStream([videoCamTrack]);
await updateMediaSenders(videoCamTrack, rtp_vid_senders);
}
}
} catch(e){
console.log(e);
return;
}
video_st = newVideoState;
}
var iceConfiguration = {
iceServers:[
{
urls:'stun:stun.l.google.com:19302',
},
{
urls:'stun:stun.l.google.com:19302',
},
],
};
async function setConnection(connid){
var connection = new RTCPeerConnection(iceConfiguration);
connection.onnegotiationneeded = async function(event) {
await setOffer(connid);
};
connection.onicecandidate = function(event) {
if(event.candidate){
serverProcess(JSON.stringify({icecandidate: event.candidate}),
connid);
}
};
connection.ontrack = function(event){
if(!remote_vid_stream[connid]){
remote_vid_stream[connid] = new MediaStream();
}
if(!remote_aud_stream[connid]){
remote_aud_stream[connid] = new MediaStream();
}
if(event.track.kind == "video"){
remote_vid_stream[connid]
.getVideoTracks()
.forEach((t)=>remote_vid_stream[connid].removeTrack(t));
remote_vid_stream[connid].addTrack(event.track);
var remoteVideoPlayer = document.getElementById("v_" + connid);
remoteVideoPlayer.srcObject = null;
remoteVideoPlayer.srcObject = remote_vid_stream[connid];
remoteVideoPlayer.load();
} else if(event.track.kind == "audio"){
remote_aud_stream[connid]
.getAudioTracks()
.forEach((t)=>remote_aud_stream[connid].removeTrack(t));
remote_aud_stream[connid].addTrack(event.track);
var remoteAudioPlayer = document.getElementById("a_" + connid);
remoteAudioPlayer.srcObject = null;
remoteAudioPlayer.srcObject = remote_aud_stream[connid];
remoteAudioPlayer.load();
}
};
peers_connection_ids[connid] = connid;
peers_connection[connid] = connection;
if(video_st == video_state.Camera ||
video_st == video_state.ScreenShare
){
if(videoCamTrack){
updateMediaSenders(videoCamTrack, rtp_vid_senders);
}
}
return connection;
}
function connection_status(connection){
if((connection && connection.connectionState == "new" ||
connection.connectionState == "connecting" ||
connection.connectionState == "connected")){
return true;
}else {
return false;
}
}
async function updateMediaSenders(track, rtp_senders){
for(var con_id in peers_connection_ids){
if(connection_status(peers_connection[con_id])){
if(rtp_senders[con_id] && rtp_senders[con_id].track){
rtp_senders[con_id].replaceTrack(track);
}else {
rtp_senders[con_id] = peers_connection[con_id].addTrack(track);
}
}
}
}
async function setOffer(connid){
var connection = peers_connection[connid];
var offer = await connection.createOffer();
await connection.setLocalDescription(offer);
serverProcess(JSON.stringify({
offer : connection.LocalDescription,
}), connid);
}
async function SDPProcess(message, from_connid){
message = JSON.parse(message);
if(message.answer){
await peers_connection[from_connid]
.setRemoteDescription(new RTCSessionDescription(message.answer));
}else if(message.offer){
if(!peers_connection[from_connid]){
await setConnection(from_connid);
}
await peers_connection[from_connid]
.setRemoteDescription(new RTCSessionDescription(message.offer));
var answer = await peers_connection[from_connid].createAnswer();
await peers_connection[from_connid].setLocalDescription(answer);
serverProcess(JSON.stringify({
answer : answer,
}), from_connid);
}else if (message.icecandidate){
if(!peers_connection[from_connid]){
await setConnection(from_connid);
}
try{
await peers_connection[from_connid].addIceCandidate(message.
icecandidate);
}catch(e){
console.log(e);
}
}
}
return {
setNewConnection: async function(connid){
await setConnection(connid);
},
init : async function(SDP_function, my_connid){
await _init(SDP_function, my_connid);
},
processClientFunc : async function(data, from_connid){
await SDPProcess(data, from_connid);
},
};
})();
var MyApp = (function(){
var socket = null;
var user_id = "";
var meeting_id = "";
function init(uid, mid){
user_id = uid;
meeting_id = mid;
$("#meetingContainer").show();
$("#me h2").text(user_id + "(ME");
document.title = user_id;
event_process_for_signaling_server();
}
function event_process_for_signaling_server(){
socket = io.connect();
var SDP_function = function(data, to_connid){
socket.emit("SDPProcess", {
message: data,
to_connid: to_connid,
});
}
socket.on("connect", () =>{
if(socket.connected){
AppProcess.init(SDP_function, socket.id);
if(user_id != "" && meeting_id != ""){
socket.emit("userconnect", {
displayName: user_id,
meetingid: meeting_id,
});
}
}
});
socket.on("inform_others_about_me", function(data){
addUser(data.other_user_id, data.connId);
AppProcess.setNewConnection(data.connId);
});
socket.on("inform_me_about_other_user", function(other_users){
if(other_users){
for(var i = 0; i<other_users.length; i++){
addUser(other_users[i].user_id,
other_users[i].connectionId);
AppProcess.setNewConnection(other_users[i].connectionId);
}
}
});
socket.on("SDPProcess", async function(data){
await AppProcess.processClientFunc(data.message, data.from_connid);
});
}
function addUser(other_user_id, connId){
var newDivId = $("#otherTamplate").clone();
newDivId = newDivId.attr("id", connId).addClass("other");
newDivId.find("h2").text(other_user_id);
newDivId.find("video").attr("id", "v_id"+connId);
newDivId.find("audio").attr("id", "a_"+connId);
newDivId.show();
$("#divUsers").append(newDivId);
}
return{
_init: function(uid, mid){
init(uid, mid);
},
};
})();
here is also the server.js file
const express = require("express");
const path = require("path");
var app = express();
var server = app.listen(3000, function(){
console.log("Listening On Port 3000");
});
const io = require("socket.io")(server,{
allowEIO3: true,
});
app.use(express.static(path.join(__dirname,"")));
var userConnections = [];
io.on("connection",(socket)=>{
console.log("socket id is", socket.id);
socket.on("userconnect", (data)=>{
console.log("userconnect", data.displayName, data.meetingid);
var other_users = userConnections.filter(
(p) => p.meeting_id == data.meetingid);
userConnections.push({
connectionId: socket.id,
user_id: data.displayName,
meeting_id: data.meetingid,
});
other_users.forEach((v) =>{
socket.to(v.connectionId).emit("inform_others_about_me", {
other_user_id: data.displayName,
connId: socket.id,
})
});
socket.emit("inform_me_about_other_user", other_users);
});
socket.on("SDPProcess", (data)=>{
socket.to(data.to_connid).emit("SDPProcess",{
message: data.message,
from_connid: socket.id,
})
})
});
i don’t know exactly where did i mess it up but i’m sure i did.
How to convert DynamoDB JSON to a regular Javascript object
How can I convert a DynamoDB JSON object to a regular object in JavaScript?
Example DynamoDB object:
{
"key1": {
"S": "val1"
},
"key2": {
"S": "val2"
},
"key3": {
"M": {
"key4": {
"M": {
"key5": {
"S": "val5"
}
}
}
}
},
"key6": {
"S": "val6"
}
}
Expected output:
{
"key1": "val1",
"key2": "val2",
"key3": {
"key4": {
"key5": "val5"
}
},
"key6": "val6"
}
how to extract an array from a string in javascript
i have a string which contains array in it and bracket , i want to extract data from it .
let vr = "- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API."
how can i dynamically identify if an array is present in this string , like take [Next.js Documentation] since it is an array. Please help me on this issue
How do I find most recent (identical) document with findOne in Mongoose
I am trying to find a document in Mongoose by using findOne ( not find ), and I want to get the most recent document even though they may have identical fields.
For example, these are the documents in Mongoose:
// Let's say this one was created a week ago in Mongoose
{
name: "John Smith",
age: 27,
industry: "finance"
}
// This one was created this morning
{
name: "John Smith",
age: 27,
industry: "healthcare"
}
So I need to do a query along the lines of this:
const client = Client.findOne({name: "John Smith"});
console.log(client) // expect the document created this morning
So when I Client.findOne by name, I’m expecting the most recent document. However Client.findOne seems to just return the old one.
Any advice?
How to group two-dimensional array by value at zero index
Let’s say I have the following two-dimensional array:
const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
What I want to do is to find all the values under first index which have common zero index value. So the result should be the following:
[[1, [1, 2]], [2, [1, 2]]]
Or maybe Map would look better:
[Map(1 => [1, 2]), Map(2 => [1, 2])]
How can I do that? With or without lodash. My solution looks a bit bloated and messy:
const array = [[1, 1], [1, 2], [2, 1], [2, 2]];
const grouppedCartItemsMap = new Map();
array.forEach((item) => {
const [locationId, contractId] = item;
if (!grouppedCartItemsMap.has(locationId)) {
grouppedCartItemsMap.set(locationId, [contractId]);
} else {
const existingItem = grouppedCartItemsMap.get(locationId);
if (!existingItem.includes(contractId)) {
grouppedCartItemsMap.set(locationId, [...existingItem, contractId]);
}
}
});
Auto filled textbox using data from a table
I have a textbox for inputting the “milled volume” of a given log(wooden log). However I want to have this field auto filled by the same logs “initial volume” which is already filled and submitted in from a separate form and stored in a separate table, how can I reference the corresponding “initial volume” when a user clicks on the text box to fill in this text box
<div class="row">
<div class="col-md-4">
<label>Volume (m<sup>3</sup>)</label>
</div>
<div class="col-md-8 form-group">
<input type="text" class="form-control" name="milled_volume" required>
</div>
</div>
Stenciljs: What is the right way to prepend/append Slot elements?
I am having some trouble with the lifecycle methods in web components.
We want to dynamically order child elements being passed in as slots.
To illustrate, this web component takes a prop, iconPos, and will determine whether the icon will be placed at the start or end of the slot.
<my-component iconPos="start">
<img src="/path/icon.svg" />
<div>{this.list}</div>
</my-component>
I haven’t had any luck getting it working with ref:
dc6b89e7.js:2926 TypeError: Cannot read properties of undefined (reading 'prepend')
Here’s what I have so far:
@State() slotElement!: HTMLDivElement;
@Prop() iconPos: 'start' | 'end';
...
private createSlots() {
switch (this.iconPos) {
case 'start':
this.slotElement.prepend(<img />);
break;
case 'end':
this.slotElement.append(<img />);
break;
default:
throw new Error(
`Invalid value `${this.iconPos}`, passed into `iconPos`. Expected valid values are `start`, `end``.
);
}
}
render() {
return (
// iconPos="start"
<parent-component>
<div ref={(el) => (this.slotElement= el as HTMLDivElement)}>
<slot></slot>
</div>
</parent-component>
)
}
I would prefer to not use a CSS solution if possible. Any help would be much appreciated!
How to Insert items into multiple Arrays in Node.js & MongoDB
This might be a weird question but I believe nothing is completely impossible.
I have a List of Users in MongoDB, each user has among other things, properties array which is currently empty.
In Excel sheet, I have a data that represents each user’s properties which I want to programmatically insert in each user’s properties array.
Importing excel sheet is fast and easy to populating each user’s properties is what gives me the problem.
I have added userId, and PropeId, from the users and the properties they bought, so Identify them as seen below

router.put(‘/importdata’, async (req, res)=>{
// upload queries
const imported = req.files.importdata;
const uploadpath = path.resolve(`public/excel_maneger/uploads/ ${imported.name}`);
if (imported.truncated) {
throw new Error("Uploaded File is too big, should not be morethan 20 MB");
}
await imported.mv(uploadpath);
const file = render.readFile(uploadpath);
const sheets = file.SheetNames;
const data = [];
for (let i = 0; i < sheets.length; i++) {
const sheetname = sheets[i];
const sheetData = render.utils.sheet_to_json(file.Sheets[sheetname]);
sheetData.forEach((item) => {
data.push(item);
});
}
try {
const users = await User.find({role: 'Customer'})
for(let i = 0; i < users.length; i++ ){
data.forEach((d) => {
if(users[i].id == d.id){
User.updateMany(
{},
{
$set: {
properties: {
propeId: d.propeId,
},
},
},
(err, d) => {
if (err) console.log(err);
}
);
}
});
}
} catch (err) {
console.log(err)
}
})
The Problem is that this code updates everyone on the Database (including non specified users) with the same information, Please I need help, I am trying to import 11 thousand users information from excel to database
The “video tag” is not working on React.js
i wanna use “video tag” for background but it doesn work.
what is wrong..?
const Auth = () => {
const covervid = '../css/video/vidbackground.mp4';
return (
<div className="Auth">
<video autoPlay={true} muted={true} loop={true} style={{ width: '100%' }}>
<source src={covervid} type="video/mp4" />
</video>
</div>
);
};
export default Auth;
Opening another view page from modal
I have a dynamic list of links in html select which can select and redirect to another page, but i want to change it and load from modal, for one viewing of different filing forms and no longer redirect to another page.
<div class="input-group input-group-sm">
<div class="input-group-prepend ">
<span class="input-group-text">Select transaction to file</span>
</div>
<select name="toFile" id="toFile" class="toFile form-control">
<option selected disabled>Choose...</option>
@try{
for (int i = 0; i < trantypetodeserialized.Count; i++){
<option value="@trantypetodeserialized[i].menu_url">@trantypetodeserialized[i].menu_name</option>
}
}
catch (Exception) { }
</select>
<div class="input-group-append">
<button class="btn btn-secondary" name="btnToFile" id="btnToFile" type="submit">Select</button>
</div>
</div>
I’m using location.href to redirect based on the selected link.
<script>
var vFile = $('#toFile').val();
$.dialog({
icon: 'fa fa-spinner fa-spin',
title: 'Redirecting',
content: 'Please Wait...',
showConfirmButton: false,
draggable: false,
closeIcon: false
});
var linkTime = setTimeout(function () {
location.href = vFile;
clearTimeout(linkTime);
$(".jconfirm").fadeOut(100);
}, 1000)
</script>
Now, i want to display all filing forms in modal but i have no idea how to do it.
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Forms</h5>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>


