I am unable to create comments. I tried using (//) and (*/) but it’s still showing the comments as normal text. I am using visual studio code as IDE this is the output I am getting
Category: javascript
Category Added in a WPeMatico Campaign
ThreeJS: Subtract object B from object A
format string to another string format
I want the newValue to keep the maskValue format, with spaces.
I have for example these two strings, the expected outcome would be this:
maskValue: "0 0000 0000 0000"
rawValue: "251551220"
As i type the maskValue changes to: "2 5155 1220 0000"
newValue = "2 5155 1220" <= expected result
2 5155 1220 0000 <= current result, it adds the rest of the zeros
This is my code:
const formattedValue = (maskValue.split('').filter(
val => val === ' ' || rawValue.split('').includes(val)
))
.join('');
Thanks for the help in advance
Reusing a single componenet
I’m trying to use a single component to render two different warning messages in a react app as the only difference in that warning message (I have both of them in a translation file) is wordings, so I tried passing language props like shown below, I’m not sure how to pass the language props while calling the component
const WarningOnIncorrectPassword = ({ onYes, onNo, isOpen, language }) => {
return (
<Typography variant="p14">{language}</Typography>
<WarningOnIncorrectPassword
language={I don't know what to pass here if I pass translation 1 it renders that text only}
isOpen={warningVisible}
onYes={handleagreewarning}
onNo={handleDisagreewarning}
/>
I tried passing a function like the below but it failed:
const checkWarningMessage=()=>{
if(it is a password error)
{
return translation_id.password_warning;
}
else
{
return translation_id.username_warning;
}
I’d appreciate any help on this thanks!
React: Consider adding an error boundary to your tree to customize error handling behavior
I know this question has been asked before but I’m having trouble getting it to work. I’m trying to render a graph using React by making nodes and links between different resources from an API. There are 2 input fields based on which the graph is rendered after clicking the Submit button. The first time the button is pressed, the graph is rendered properly. However when I change the input and press the button, I get the above error. I was getting “Can’t perform a React state update on an unmounted component” error before but then I updated my React version and now I get this error.
My guess is that this error is pretty similar to what I was getting before. I think there needs to be some sort of a cleanup function to get rid of this error when component is unMounted. Also, I’m using state variables but I’m not using useEffect() in my code anywhere. When the submit button is pressed, I just call an asynchronous function which makes the API call.
So template code is something like
export default function App(props) {
let[nodes,setNodeDataFromAPI]=useState([])
let[links,setLinkDataFromAPI]=useState([])
let handleSubmit=(event)=>{ // method called when form is submitted
getData()
}
async function getData() {
graphLinks=[]
graphNodes=[]
//make axios call using await
//get all data about nodes and links for the graph
// iterate through fetched data and populate graphLinks and graphNodes arrays
setNodeDataFromAPI(graphNodes)
setLinkDataFromAPI(graphLinks)
}
return(
<Graph linksData={links} nodesData={nodes} />
)
Is is possible to do arithmetc operations on 15 digit numbers with decimal value in Javascript?
I am trying to perform an arithmetic operation on 15 digit numbers with decimal value in Java Script.
But, I am getting wrong decimal value in result.
The issue is reproducible in other JS functions such as Round(), Floor(), toFixed() etc.
This seems to be a Javascript language limitation (64bit).
Do we have any solution/alternative for this ?
Convert nodes that consists of nested objects, strings, array into an unordered list (Javascript)
I have this variable value of
["test", { testone: "check", filter: [{ testtwo: "ignore", cancel: ["3.2"]}], "testthree"}].
What I want to do is to display this in an unordered list below.
. test
. check
. ignore
. 3.2
. testthree
I can convert it to a list if its in an array or array object, nested kinda confused me. I am thinking that a recursive function (correct me if i am wrong) can be used here and this is my first time solving a complex problem with javascript, care to share some sample how to solve this? Thanks
Sending an integer array in graphQL
I have a scalar integer array in the following format-
{ "values" : [10,20,30] }
and I want to send it using graphQL. How to send the scalar values present in the array since they haven’t been mapped? Any help would be appreciated. TIA!!
navigator.mediaSession CORS, nestJS
i am using nestJS as server framework which is using cors middleware. i’ve set up an origin options which are
const whitelist = [...]
app.enableCors({credentials: true, origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}})
on my front i’ve specified crossorigin=’use-credentials’ in all <img / > and <audio / > elements, but how to specify this in mediaSession?
useEffect(() => {
if ('mediaSession' in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: name || 'Unknown',
artist: author || 'Unknown',
artwork: [
{ src: cover as string || '', sizes: '256x256', type: 'image/png' },
{ src: cover as string || '', sizes: '512x512', type: 'image/png' }
]
});
}
}, [name, author, cover])
my server blocks requests from mediaSession artworks since the first parameter of origin function in cors middleware is undefined
p.s. cover in useEffect is an url of the image on my server
initialState array wont show api info (Redux)
I don’t get why dispatch is not sendin list: [] the information, only info I got is list: [] has it’s property in never[].
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
export const userSlice = createSlice({
name: "users",
initialState: {
list: [] /* (property) list: never[] */
},
reducers: {
setUserList: (state, action) => {
state.list = action.payload;
}
},
});
export const { setUserList } = userSlice.actions;
export default userSlice.reducer;
export const fetchAllUsers = () => (dispatch) => {
axios
.get('https://reqres.in/api/users?page=2')
.then((response) => {
dispatch(setUserList(response.data.data));
})
.catch((error) => console.log(error))
};
I want to push files to particular array . if user selects title based on that title i want to push the files to that particular title array
{
state.tags.map((data)=>(
<h5 onClick={()=>addDocs(data)}>{data}</h5>
))
}
const addDocs=(data)=>{
console.log(data)
}
suppose if data is hitman so want to put the files to that array and on next iteration if the data is spiderman send the next file to that array but the file should not be removed from first array of hitman
Displaying Shopify buy button twice on a page with JavaScript Customization (document.getElementById to document.querySelectorAll)
I need to display a Shopify buy button twice (links to the same product) on a web page because I have a smartphone table and pc table.
With the generated code I got from Shopify, the button only appears on one table because of this JavaScript:
ShopifyBuy.UI.onReady(client).then(function (ui) {
ui.createComponent('product', {
id: '7369316827224',
node: document.getElementById('buybutton'),
The “document.getElementById” only allows for an ID to display once.
So in order to be able return all elements with id=”buybutton”, I changed it to the following:
ShopifyBuy.UI.onReady(client).then(function (ui) {
ui.createComponent('product', {
id: '7369316827224',
node: document.querySelectorAll('#buybutton'),
Additionally, I changed the HTML from
<div id='buybutton'></div>
to
<div id="#buybutton"></div>
However, these changes cause the buy button to disappear from both tables.
I have also tried changing it to getElementByClass
node: document.getElementByClass('buybutton'),
with HTML <div class="buybutton"></div> but this also did not work (nothing appeared).
What am I doing wrong? Is there another way to do what I want to do?
Here is the entire script from Shopify for reference (some info is replaced with “000” for privacy reasons):
/*<![CDATA[*/
(function () {
var scriptURL = 'https://sdks.shopifycdn.com/buy-button/latest/buy-button-storefront.min.js';
if (window.ShopifyBuy) {
if (window.ShopifyBuy.UI) {
ShopifyBuyInit();
} else {
loadScript();
}
} else {
loadScript();
}
function loadScript() {
var script = document.createElement('script');
script.async = true;
script.src = scriptURL;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);
script.onload = ShopifyBuyInit;
}
function ShopifyBuyInit() {
var client = ShopifyBuy.buildClient({
domain: 'sugatsune-uk.myshopify.com',
storefrontAccessToken: '000',
});
ShopifyBuy.UI.onReady(client).then(function (ui) {
ui.createComponent('product', {
id: '7369316827224',
node: document.getElementById('buybutton'),
moneyFormat: '%C2%A3%7B%7Bamount%7D%7D',
options: {
"product": {
"styles": {
"product": {
"@media (min-width: 601px)": {
"max-width": "calc(25% - 20px)",
"margin-left": "20px",
"margin-bottom": "50px"
}
},
"button": {
"font-weight": "bold",
"font-size": "12px",
"padding-top": "6px",
"padding-bottom": "6px",
":hover": {
"background-color": "#2d2d2d"
},
"background-color": "#000000",
":focus": {
"background-color": "#2d2d2d"
},
"padding-left": "6px",
"padding-right": "6px"
},
"quantityInput": {
"font-size": "12px",
"max-width": "20px",
"padding-top": "6px",
"padding-bottom": "6px"
}
},
"contents": {
"img": false,
"button": false,
"buttonWithQuantity": true,
"title": false,
"price": false
},
"text": {
"button": "Add to cart"
}
},
"productSet": {
"styles": {
"products": {
"@media (min-width: 601px)": {
"margin-left": "-20px"
}
}
}
},
"modalProduct": {
"contents": {
"img": false,
"imgWithCarousel": true,
"button": false,
"buttonWithQuantity": true
},
"styles": {
"product": {
"@media (min-width: 601px)": {
"max-width": "100%",
"margin-left": "0px",
"margin-bottom": "0px"
}
},
"button": {
"font-weight": "bold",
"font-size": "12px",
"padding-top": "6px",
"padding-bottom": "6px",
":hover": {
"background-color": "#2d2d2d"
},
"background-color": "#000000",
":focus": {
"background-color": "#2d2d2d"
},
"padding-left": "6px",
"padding-right": "6px"
},
"quantityInput": {
"font-size": "12px",
"max-width": "20px",
"padding-top": "5px",
"padding-bottom": "5px"
}
},
"text": {
"button": "Add to cart"
}
},
"option": {},
"cart": {
"styles": {
"button": {
"font-weight": "bold",
"font-size": "14px",
"padding-top": "15px",
"padding-bottom": "15px",
":hover": {
"background-color": "#2d2d2d"
},
"background-color": "#000000",
":focus": {
"background-color": "#2d2d2d"
}
}
},
"text": {
"total": "Subtotal",
"button": "Checkout"
}
},
"toggle": {
"styles": {
"toggle": {
"font-weight": "bold",
"background-color": "#000000",
":hover": {
"background-color": "#2d2d2d"
},
":focus": {
"background-color": "#2d2d2d"
}
},
"count": {
"font-size": "14px"
}
}
}
},
});
});
}
})();
/*]]>*/
Question about Javascript code execution speed regarding the order in which their file are declared [duplicate]
Does the order of javascript files affect the actual speed of the scripts? I am thinking that maybe the browser would be able to read first the scripts in the first file like if you have 5 js files like this:
<script src="jsfile1.js"></script>
<script src="jsfile2.js"></script>
<script src="jsfile3.js"></script>
<script src="jsfile4.js"></script>
<script src="jsfile5.js"></script>
and for testing, if I have the function, say:
function retrieve_ajax_data_then_render_page(){
//some functions
}
would it be faster for the browser to execute the function if it is in jsfile1.js? or everything will be hoisted at the same level once the browser has parsed the js files? Thanks!
what is the difference between module.exports.default and module.exports.tags?
what is the difference between module.exports.default and module.exports.tags ?
and how to work with these two together like
const funcA = () => {
//some code
}
module.exports.tags = ["all", "test"]
module.exports.default = funcA ;
or can someone share a link where I can learn about ?
How to merge multiple objects in a array and sum the values in JavaScript?
I don’t have a solution to merge multiple objects in an array and sum the values.
Before:
const arr = [
{a: 2, b: 2, d: 1, total: 5},
{a: 3, b: 1, c: 5, d: 1, total: 10}
]
After:
const obj = {a: 5, b: 3, d: 2, c: 5, total: 15}

