I am trying to use Cloudflare’s turnstile documented here with the execution option. I am calling turnstile.execute in an async function called after a button press, but the function doesn’t seem to be wait for the challenge to finish before continuing. Is there a way I can await or something similar on turnstile.execute so that I am able to use the token in the callback later on in the function?
Category: javascript
Category Added in a WPeMatico Campaign
Ability to scope media queries or screen size to element
I think the simplest way to explain the question is with an example.
Say I have some interactive builder that allows users to drag and move elements etc.. as well as apply certain predefined styles. These styles are responsive and will use media queries of the type screen and (min-width: 768px) as an example.
Then in the app I would like to provide a preview element that can be resized, very similar to chrome or any browser mobile preview. So I’ve been looking for a way to somehow override either the screen size or media query for all styles applied to elements that descendants of that preview element.
I hope that’s clear enough. So far I’ve seen something about CSS container queries but wasn’t quite able to confirm whether that would work in this case. To clarify, these same styles, are styles that I would like to then work anywhere else, even outside of this preview.
Appreciate any help!
Cant render an array of object from context file
for some reason i cant render my array of objects ‘data’. I’m using react and context hook. I dont get any error in my browser.
Here is the repository of this problem
https://github.com/santanafx/teste-context
file index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { ContextProvider } from './context/globalContext';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ContextProvider>
<App />
</ContextProvider>
</React.StrictMode>
);
file App.js
import React from 'react'
import './App.css';
import { Context } from './context/globalContext';
function App() {
const { data } = React.useContext(Context);
return (
<div >
{data.map((element) => {
<div key={data.id}>
<div>{element.id}</div>
<div>{element.descricao}</div>
<div>{element.edicao}</div>
</div>
})}
</div>
);
}
export default App;“`
file globalContext.js
import React from 'react'
export const Context = React.createContext();
export const ContextProvider = ({ children }) => {
var data = [{
id: 'teste1',
edicao: '1',
descricao: '2',
},
{
id: 'teste2',
edicao: '1',
descricao: '2',
},
{
id: 'teste3',
edicao: '1',
descricao: '2',
}]
return (
<Context.Provider value={{ data }}>
{children}
</Context.Provider>
)
}
I tried to use react hook of state at my context file but i didnt have success. For some reason it seems that i cant render an object from my context hook.
How do I make my popup in my code functional?
I am actively creating a web application that I would like to have a pop up functionality aspect on a specific feature layer and it doesn’t work.
I’ve looked at templates in ArcGIS Maps SDK for JavaScript and followed along but regardless it just isn’t functioning like its supposed to. This is what my code looks like so far but it just doesn’t work:
var popupAdminDetails = {
"title": "<b>{OFFICE_NAME}</b>",
"content": [{
type: "fields",
fieldInfos: [
{
fieldName: "REGION",
label: "<b>REGION<b>"
},{
fieldName: "FULL_ADDRESS",
label: "<b>ADDRESS</b>"
},{
fieldName: "LOCATION",
label: "<b>LOCATION<b>"
}]},{
type: "media", // MediaContentElement
mediaInfos: [
{
//title: "<b>test</b>",
type: "image",
//caption: "office",
value: {
sourceURL:
"officeimgs/{GEO_TAG}.JPG"
}
}]
}]
//"content": "<b>REGION:</b> {REGION}<br><b>ADDRESS:</b> {FULL_ADDRESS}<br><b>LOCATION:</b> {LOCATION}"
}
Please see my codepen here for all my code: https://codepen.io/chesouye/pen/XWxyRvx
React await Promise are usable/compatible with Redux Saga flow?
In my React project I’m using Redux with SAGA, this mean that when I need to get data from APIs I dispatch an action catched by a SAGA that make a axios request and when the respone is received a SUCCESS actions is launched with the following reducer update.
The problem I’m experiencing is that trying to implements a Promise inside a component for await a response before execute another function, the other function is executed before the Promise is completed.
I’m not sure if the problem is due to a wrong usage/implementation of Promise or if Promise are not compatible with Redux/saga flow.
In my case, unfortunatelly, I cannot use the Redux/Saga to set a field in a reducer and then use it as dependency in a useEffect to trigger the callApplyFilter function, so I need to find a way to use Promise.
const MyComponent = (props) => {
const dispatch = useDispatch();
// This is the function that dispatch the action to related SAGA and that I want to wait reponse
const refreshTableData = () => {
dispatch(Actions.getDataFromApi());
};
async function callRefreshData() {
return new Promise(function(resolve, reject) { //Create Promise
refreshTableData();
resolve();
});
}
const callApplyFilter = () => {
props.debouncedSearch();
};
const handleRefreshDataAndApplyFilters = async () => {
await Promise.all([callRefreshData()]); //Add Promise
callApplyFilter();// This is the function that I want execute only after refreshTableData() is completed and data from APIs returned and saved to reduces
};
return (
<React.Fragment>
<Toolbar>
<Grid container direction="row" justifyContent="space-between" alignItems="center">
<ToolbarIconButton
onClick={(event) => handleRefreshDataAndApplyFilters()}
/>
</Grid>
</Toolbar>
)}
</React.Fragment>);
};
Acessar todos os objetos do array [closed]
estou com um problema na minha aplicação no React com uma api, vocês poderiam me ajudar?
estou querendo fazer um sistema de rota dinâmica a partir da api da riot Valorant, porem toda vez que eu consigo acessar a rota dinamica do objeto dentro do array, ou seja, ir para uma pagina de “mais informações”, eu consigo acessar o objeto desejado, porem não consigo mostrar na tela os dados do objeto, porque o resultado esta chegando undefined:
//ARQUIVO ONDE REALIZO A REQUISIÇÃO NA API
import { useEffect, useState } from "react";
export default function FechApi(url){
const [agent, setAgent] = useState([]);
useEffect(() =>{
async function getValorantApi() {
try {
const url1 = await fetch(url);
const json = await url1.json();
const data = await json.data
setAgent(data);
console.log(data);
} catch (error) {
console.log("error:", error);
}
}
getValorantApi();
},[url])
return{agent}
}
//ARQUIVO ONDE EU MOSTRO OS DADOS DINAMICOS DE ACORDO COM AS ROTAS
import { useParams } from "react-router-dom";
import FechApi from "../../hooks/Hooks";
export default function Product() {
const { id } = useParams();
const url = 'https://valorant-api.com/v1/agents/' + id
const {agente: agentes} = FechApi(url)
console.log(agentes)
return (
<>
<p>id do agente: {id}</p>
{agentes && (
<p key={agentes.displayname} className="box-item"></p>
)}
</>
);
}
enter image description here //imagem mostrando o terminal e oque está chegando
eu tentei enviar a url dinamica (url com o id do personagem) para a função FechApi,mas ela me retorna os dados com undefined
removeChild() working only for first child in list rendered with insertAdjacentHTML
I have the following function for iterating through an array of activities and displaying them. The function also includes a trash-icon that is meant to clear away any specific item that is selected by clicking:
const renderList = (activities) => {
const display = document.getElementById('task-list-display');
activities.forEach((activity) => {
display.insertAdjacentHTML('beforeend', `
<li id="task-item" class="task-item">
<div class="chk-descr">
<input
data-a1="${activity.index}"
type="checkbox"
name="completed"
class="completed"
/>
<p data-b1="${activity.index}" class="description" contenteditable="true">${activity.description}</p>
</div>
<i class="clear-item fa fa-trash"/></i>
</li>
`);
const listItem = document.querySelectorAll('.task-item')[0];
const clearItem = document.querySelectorAll('.clear-item')[0];
clearItem.addEventListener('click', () => {
display.removeChild(listItem);
});
});
};
The display is working perfectly. However, I am having no success in clearing the items. No success, that is, unless the item selected is the one at the very top of the list. In that case, the item is removed from display, but I obtain the following error:
Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
When clicking on the items below that one, there is no response at all.
I understand that this has to do with using insertAdjacentHTML to insert the items into display but I do not know what I can use in its stead. remove(listItem) also does not work.
Thanks in advance to anyone that can enlighten me in regards to this matter.
Javascript “this” from element eventlistener returns window [duplicate]
I’m working on a accordion, I have four html elements with class accordionItemHeading
This is my js code, why does it log four times window on page load? also why does it log something at all isn’t the function supposed to be called only at click?
document.addEventListener("DOMContentLoaded", (e) => {
let accordionHeadings = document.querySelectorAll('.accordionItemHeading');
if(accordionHeadings.length){
for (let i=0; i < accordionHeadings.length; i++) {
accordionHeadings[i].addEventListener('click', toggleHeading(e), false);
}
}
function toggleHeading(e){
console.log(this)
}
});
How to filter an array by two params?
I’m expecting to filter an array with next params:
- By selected countries
- By score. If score more than 10 or more than 20
I’m forming an object with input fields, and sending it to store in purpose to filter the initial array by two params, the country and the score at the same time. But the function is filtering only by countries, not scores and countries.
//Store
function filterAll(data) {
let filteredUsers = this.initialArray.filter((u) => {
const filteringKeys = Object.keys(data);
return filteringKeys.every((k) =>
data[k].value !== '' || data[k].value !== 'All'
? u['country'] === data['country'].value &&
u['score'] < data['score'].value
: true
);
});
}
data= {
countries, // Usa or Canada
scores //more than 10 or more than 20
}
Vuetify: what does emitting an input event do if nothing seems to explicitly use an input event?
We have a Vuetify 3 component called FilterPanel; a simplified version follows:
<template>
<div>
<v-container>
<v-row>
<v-col cols="3">
<v-select v-model="field" :items="fields" :menu-props="{ auto: true }">
<v-field />
</v-select>
</v-col>
<v-col>
<v-text-field v-model="text" :type="(formats && formats[field]) || 'text'" @keyup.enter="add" />
</v-col>
<v-col cols="2">
<v-btn @click="add()">
Add Filter
<v-icon end theme="dark"> mdi-filter-plus </v-icon>
</v-btn>
</v-col>
</v-row>
</v-container>
<v-chip>
... removed for brevity
</v-chip>
</div>
</template>
The Vuetify 2 version of this was similar:
<template>
<div>
<v-text-field v-model="text" :type="(formats && formats[field]) || 'text'" @keyup.enter="add">
<v-select slot="prepend-inner" v-model="field" :items="fields" menu-props="auto" />
<v-btn slot="append" @click="add()" >
Add Filter
<v-icon right dark>mdi-filter-plus</v-icon>
</v-btn>
</v-text-field>
<v-chip>
... removed for brevity
</v-chip>
</div>
</template>
Later on in the file (in the <scripts>), there are these lines in various methods on the exported object:
this.$emit('input', { ...this.value, ...qFields })
this.$emit('input', { ...this.value, [this.field]: this.text })
this.$emit('input', omit(this.value, key))
In the Vuetify 2 version, this.value basically seemed to be equivalent to { [this.field]: this.text } (except w/ getters and setters). I’m not sure if it’s because of the reorganized code or because of a Vuetify change, but this.value now seems to be undefined.
What exactly are these emits supposed to accomplish? I don’t see any @input anywhere in our codebase, and I looked at various components in the tree from Vuetify, and none explicitly mention an input event, either.
Ultimately, what I’m trying to figure out is whether I should:
- just delete the emits
- do something funky to reconstruct
this.value(e.g.
this.$emit('input', { ...{ [this.field]: this.text }, ...qFields })) - change these based on some change in Vuetify 3 that weren’t in
the migration guide? I did notice this:@input event has been replaced by @update:model-value on components that support v-model usage.but I’m not sure exactly what needs to be done if that’s relevant – change the first emit parameter, but then what about the second parameter?
Thank you!
Send array of images from Angular to ExpressJS server via POST using multer
I have an Angular form that accepts multiple images and I want to send those to my ExpressJS server with a POST request. I managed to do it for a SINGLE picture with multer and FormData, but I’m struggling to get it done for more than 1 picture.
Here’s my server side code:
const storage = multer.memoryStorage();
let upload = multer({storage: storage});
router.post('/uploadPictures', upload.array("pictures", 5), uploadPicture);
The uploadPicture function just displays req.file, req.body & req.files.
Here’s my Angular code.
Component:
pictures: any[];
async uploadProperty() {
if (this.uploadPropertyForm.valid) {
const formData = new FormData();
for (let i = 0; i < this.pictures.length; i += 1) {
formData.set(`pictures[${i}]`, this.pictures[i]);
}
this.propertiesService
.uploadPictures(formData)
.subscribe((response) => {
console.log(response);
});
}
}
Service:
uploadPictures(pictures: FormData) {
const url = `${this.baseUrl}/properties/uploadPictures`;
return this.http.post(url, pictures);
}
I tried a few different things to make it work:
- Using the method formData.append(). This way req.file is undefined, even for a single image.
- Using the for loop in different ways:
for (let i = 0; i < this.pictures.length; i += 1) {
formData.set(`pictures[]`, this.pictures[i]);
}
or
for (let i = 0; i < this.pictures.length; i += 1) {
formData.append(`pictures[]`, this.pictures[i]);
}
When I use formData.append(), req.file & req.files is undefined.
When I use formData.set() I get the following multer error:
MulterError: Unexpected field at wrappedFileFilter (F:projectNamenode_modulesmulterindex.js:40:19) at Multipart.<anonymous> (F:projectNamenode_modulesmulterlibmake-middleware.js:107:7) at Multipart.emit (node:events:513:28) at Multipart.emit (node:domain:489:12) at HeaderParser.cb (F:projectNamenode_modulesbusboylibtypesmultipart.js:358:14) at HeaderParser.push (F:projectNamenode_modulesbusboylibtypesmultipart.js:162:20) at SBMH.ssCb [as _cb] (F:projectNamenode_modulesbusboylibtypesmultipart.js:394:37) at feed (F:projectNamenode_modulesstreamsearchlibsbmh.js:248:10) at SBMH.push (F:projectNamenode_modulesstreamsearchlibsbmh.js:104:16) at Multipart._write (F:projectNamenode_modulesbusboylibtypesmultipart.js:567:19)
As you can see the message doesn’t provide much information about where or what’s causing the problem so I’m kind of lost.
I’m only trying to upload 2 images so size shouldn’t be a problem.
How to integrate ‘fs’ with webpack 5
I want to count number of files in a directory using javascript. I am using Webpack 5 for bundling. My js file is running fine with node (node index.js) when I set type=’module’ in package.json. But when I am calling it from html, it is not working
JS file (index.js)
import fs from "fs"
const pathToDirectory = './asset/idea/democracy';
fs.readdir(pathToDirectory, (error, files) => {
if (error) {
console.log(error);
} else {
console.log(files);
console.log(files.length)
;
}
});
package.json
{
"name": "swaraj",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "newsAddEdit.js",
"dependencies": {
"@popperjs/core": "^2.11.8",
"browserify-fs": "^1.0.0",
"firebase": "^9.22.0",
"html-webpack-plugin": "^5.5.1",
"lodash": "^4.17.21",
"stream-browserify": "^3.0.0",
"webpack-node-externals": "^3.0.0"
},
"devDependencies": {
"@babel/core": "^7.21.8",
"@babel/preset-env": "^7.21.5",
"babel-loader": "^9.1.2",
"clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^11.0.0",
"css-loader": "^6.8.1",
"css-minimizer-webpack-plugin": "^5.0.0",
"favicons": "^7.1.2",
"favicons-webpack-plugin": "^6.0.0",
"mini-css-extract-plugin": "^2.7.6",
"style-loader": "^3.3.3",
"webpack": "^5.82.1",
"webpack-cli": "^5.1.1",
"webpack-dev-server": "^4.15.0"
},
"scripts": {
"start": "webpack-dev-server --config=webpack.config.js",
"watch": "webpack --watch",
"build": "NODE_ENV=production webpack --config=webpack.config.js",
"build:dev": "webpack",
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Webpack.config.js
const path = require('path');
const webpack = require('webpack'); // to access built-in plugins
const mode = process.env.NODE_ENV || "development";
const target = process.env.NODE_ENV === "production" ? "browserslist" : "web";
module.exports = {
resolve: {
fallback: {
stream: require.resolve('stream-browserify'),
},
},
mode: mode,
devtool: 'eval-source-map',
entry: {
index: './src/index.js',
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name]Bundle.js', // [contenthash]
clean: true,
},
watch: true,
module: {
rules: [
{
test: /.css$/i,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
],
},
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
},
{
test: /.(png|svg|jpg|jpeg|gif)$/,
type: 'asset/resource',
},
],
// loaders: [
// { test: /.hbs$/, loader: "handlebars-loader" }
// ],
},
};
HTML file(index.html)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<body>
<div id="numberFiles"></div>
</body>
<script type="module" src="./dist/indexBundle.js"></script>
</html>
Why is my API key showing as ‘undefined’ when I set it up as an environment variable in my Node.js backend server built with Express?
API_KEY is showing as ‘undefined’ when I set it up as an environment variable
My API_KEY is showing as ‘undefined’ when I set it up as an environment variable. The API call works when I hard code the API Key, so it’s not an issue with the key. I can also see that value of it is ‘undefined’ in the logs. I am trying to access it from a backend server (server.js) built with express. I created a separate .env file in the root of the project’s backend directory (at the same level with server.js).
I’ve installed dot env and included ‘import dotenv from dot env’ and dotenv.config in my server.js file. I’m including my server.js, .env, and package.json files below.
server.js
import express from "express";
import cors from "cors";
import axios from "axios";
import dotenv from "dotenv";
dotenv.config();
const PORT = 8000;
const app = express();
app.use(cors());
app.get("/hello", (req, res) => {
res.json("Hello World");
});
app.get("/test-cases", async (req, res) => {
const API_KEY = process.env.REACT_APP_OPENAI_API_KEY;
console.log(API_KEY);
.env
# Not a real API KEY!!!!!
REACT_APP_OPENAI_API_KEY=sk-NgPdmiXotwLWvasdsddsfkFJG4bnvnod3BwRPTsPaeUv
package.json
{
"name": "test-genie-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start-backend": "nodemon src/server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^1.4.0",
"cors": "^2.8.5",
"dotenv": "^16.1.0",
"express": "^4.18.2"
}
}
file upload won’t upload .Json file
I’m working on my first react project and I have an upload button through which the user can upload a set of files. I noticed that the file upload works perfectly for all file extensions, except for .json files. I’m not quite sure why that is, can anyone take a look at my addFile function? openUploadStream is the function given by mongoDB for GridFS storage of files.
const addFile = async (req, res) => {
const { filename } = req.body
const path = "cache\" + filename //all files are stored in the cache folder
const uploadStream = fs.createReadStream(path).
pipe(bucket.openUploadStream(filename)) //store the file as the filename}
res.status(200).json({id : uploadStream.id}) //return unique id of file in the db
}
and in the frontend I call the API using axios
await axios.post('/api/filesRoute/fs', { filename : filename })
.then((json) => {
console.log('Success uploading', filename)
raws.push(json.data.id)
})
How to return several data params to the function vue/js?
In the vuex actions I’m trying to filter an array with two different props which are passed to the action as a data object. I’ve writen how filtering by one filter param but I’m expecting to filter with both data params (contry and score) at the same time at one action. Later to render a single filtered list. Both of data params are options of a select tag.
//Child Component
const filterUsers = () => {
let data = {
country, //trying to filter both items
score, //trying to filter both items
};
usersStore.filterAll(data);
};
// Store
state: {
users: [...],
filteredUsers: [...]
}
async filterAll(data) {
this.filteredUsers = [...this.users];
this.filteredUsers = this.filteredUsers.filter((u) => {
const filteringKeys = Object.keys(data);
return filteringKeys.every((c) => //trying to pass c for country and s for score at the same time
data[c].value !== '' || data[c].value !== 'All'
? u['country'] === data['country'].value
: true
);
});
},