Category: javascript
Category Added in a WPeMatico Campaign
Props not being passed through components
Is there any reason the below code wouldn’t work, It being populated in the console fine but as soon as I log this data in the child component it says its an empty array
I am trying to pass processedSessions to AllSessions but its being logged as an empty array in AllSessions but a populated on in App.js which is the code you see below
I have tried manually creating variable that is an array and passing this through works fine but effectively I pasting an object from my console into this object so it isn’t any different
import React, { useState } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import AddSession from "./pages/AddSession";
import Home from "./pages/Home";
import AllSessions from "./components/AllSessions";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
// import { AddSessionForm } from "./components/AddSessionForm";
// import NavigationButtons from "./components/NavigationButtons";
function App() {
const [allSessions, setAllSessions] = useState([]);
const updateAllSessions = (newSession) => {
console.log("Updating sessions with:", newSession);
setAllSessions((prevSessions) => [...prevSessions, newSession]);
};
// Map over allSessions to process the data
const processedSessions = allSessions.map((session) => ({
date: session.date,
exercise: session.exercise,
reps: session.reps,
sets: session.sets,
weight: session.weight,
}));
const sessionArray = [
{
date: "1213",
exercise: "Bench",
reps: 23423,
sets: 42353,
weight: 5435,
},
];
console.log("Current allSessions:", processedSessions);
return (
<Router>
<Routes>
{/* Pass the processedSessions to AllSessions */}
<Route
path="/AllSessions"
element={<AllSessions allSessions={processedSessions} />}
/>
<Route
path="/AddSession"
element={<AddSession updateAllSessions={updateAllSessions} />}
/>
<Route path="/" element={<Home />} />
</Routes>
</Router>
);
}
export default App;
mark 3 words characters using java
so I’m trying to create func to find 3 letters words for a long text.
const fullstory =
"One advanced etc etc"
document.querySelector("#story").innerHTML = fullstory;
const cutspace = fullstory.split(" ");
document.querySelector("#three").addEventListener("click", find3);
function find3() {
for (i = 0; i < cutspace.length; i++)
if (cutspace[i].length<=3){
//cutspace[i].style // not working
};
}
what am i missing?
right way to clear SWR cache
SWR recommends using
mutate(
key => true, // which cache keys are updated
undefined, // update cache data to `undefined`
{ revalidate: false } // do not revalidate
)
to clear cache. And I can not decide between
import {mutate} from "swr"
and
const {mutate} = useSWRConfig()
which is better in this case ?
Convert string to variable name in Typescript
I am trying to convert a string to a variable name in Typescript. I am trying to use the string as an src in an img tag. I am using React.
An abbreviated version of what I am trying to do:
import example from './example.png';
function Foo () {
const str = 'example';
return (
<img src={CONTENTS_OF_str_AS_A_VARIABLE} />
);
};
export default Foo;
Note that in my actual code I am building the contents of str dynamically, so I can’t just type 'example' in the src of the img.
I looked online and found I can use window to convert the string to a variable, but when I try that I get the following error: Element implicitly has an 'any' type because index expression is not of type 'number'. ts(7015). My updated code looks something like this:
import example from './example.png';
function Foo () {
const str = 'example';
return (
<img src={window[str]} />
);
};
export default Foo;
Everything I find online addresses how to use window, but not how to type it. How can I fix this so my code works correctly?
Decrypt/Reverse Engineer this function. Using CryptoJS and VanillaJS [closed]
So someone scratched up this function for me; they suggest storing the hash in a database and using it as a reference for the original string. However i’m just wondering with whats there is it possible to easily decrypt the string back to its original? I’m looking to reverse engineer the hash varibale that is being logged in the console back into the original string that was called in the beggining of the function.
<script type="text/javascript">
function hash(s){
e = [];
d = '';
for(i = 0; i < s.length; i++){
e.push(s.charCodeAt(i));
}
keys = [];
for(i = 0; i < e.length; i++){
keys.push([Number((e[i] / 8).toString().substr(0, (e[i] / 8).toString().indexOf(".") == -1 ? (e[i] / 8).toString().length : (e[i] / 8).toString().indexOf("."))) + 2 > 9 ? [Number((Number((e[i] / 8).toString().substr(0, (e[i] / 8).toString().indexOf(".") == -1 ? (e[i] / 8).toString().length : (e[i] / 8).toString().indexOf("."))) + 2).toString().substr(0, 1)) + 2, Number((Number((e[i] / 8).toString().substr(0, (e[i] / 8).toString().indexOf(".") == -1 ? (e[i] / 8).toString().length : (e[i] / 8).toString().indexOf("."))) + 1).toString().substr(1, 2)) + 1] : Number((e[i] / 8).toString().substr(0, (e[i] / 8).toString().indexOf(".") == -1 ? (e[i] / 8).toString().length : (e[i] / 8).toString().indexOf("."))) + 2, Number(e[i] % 9) + 2]);
}
squares = 1;
for(i = 0; i < keys.length; i++){
if(typeof keys[i][0] == 'object'){
squares *= keys[i][0][0] * keys[i][0][0];
squares *= keys[i][0][1] * keys[i][0][1];
}else{
squares *= keys[i][0] * keys[i][0];
}
squares *= keys[i][1] * keys[i][1];
}
divide = squares;
divide = divide;
r = 0;
while(divide.toString().length > 21){
r = r + 1;
divide = Number(divide) / 714285;
}
sqrt = Math.sqrt(divide);
hex = sqrt / 333.33;
base64x = CryptoJS.enc.Base64.parse(hex.toString()).toString(CryptoJS.enc.Base64);
base64 = "_" + base64x;
i = 0;
while(base64x.length < 26){
base64x = base64x.charCodeAt(i) + base64x;
i = i + 1;
}
hash = r + "_" + base64x;
hash = CryptoJS.enc.Base64.parse(hash).toString();
console.log(s, hash);
}
}
hash('Something tediously long to describe with infinite depth.');
How to fetch N most recent entries from DynamoDB using Lambda Function
I have items in a DDB table with a field labeled Timestamp that has date/time string values such as these: 2023-11-14T01:22:53.945Z
All I want to do is query my database to return N entries sorted from most recent based on this timestamp value. I’m reading a bunch of posts talking about GSI … ranges … sort keys. A little overwhelming and not sure how to approach.
I don’t really have a code example, just tried a few things from ChatGPT and other SO posts, but some of them involve having the Timestamp as secondary keys, some as GSI’s, not sure what the proper approach is. (using JavaScript)
Browser stuck at loading when calling reject callback
Resolve is logging fine but reject isn’t
let promise = new Promise(function (resolve, rej) {
let isfulFilled = false
isfulFilled ? resolve('Resolved!') : rej('Rejected!')
})
promise
.then(console.log)
.catch(console.log)
I can only make it work when I insert reject in setTimeout.
How can I make it work without setTimeout?
How to run Jest with ES6 modules in node_modules
I have a simple test that is calling a function imported from an ES module dependency. Jest throws an error SyntaxError: Unexpected token 'export'. I can add the offending module to the transformIgnorePatterns patterns array in the Jest config, but then I get the same error for another ES module, until my transformIgnorePatterns array becomes very big. Clearly I am missing something. What is the best way to handle this?
I have 1 dependency, which is @mdx-js/mdx. I have imported the named export in foo.js:
// foo.js
import { compile } from "@mdx-js/mdx";
And then a test that imports foo.js:
// foo.test.js
import foo from "./foo";
describe("foo", () => {
it("should do something", () => {});
});
Running jest throws this error:
/Users/tylersargent/Code/mdx-transformer/node_modules/@mdx-js/mdx/index.js:12
export {compile, compileSync} from './lib/compile.js'
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import { compile } from "@mdx-js/mdx";
| ^
2 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
at Object.require (src/foo.js:1:1)
at Object.require (src/foo.test.js:1:1)
I can add @mdx-js/mdx to the transformIgnorePatterns, but then I get the next module I need to transform, and on and on.
I have seen a similar question here How to setup jest with node_modules that use es6 but I am looking for a way to handle this that does not require adding so many modules to the transformIgnorePatterns entry.
I have provided a repo here: https://github.com/tsargent/mdx-poc-2
To see the issue, clone the repo and run:
yarn install
yarn test
Then see the error. Add @mdx-js/mdx to the transformIgnorePatterns config in jest.config.js:
transformIgnorePatterns: ["/node_modules/(?!(@mdx-js/mdx)/)"]
Run jest again, and repeat…
Live View Map not showing requests
i am running it on localhost (XAMPP) on my Mac, i went to localhost:3000 and devtools console is not showing errors but when i try to load a page is not showing it on index.html map. my logs folder is correct, port is 3000, Maybe someone can figure out about it: https://github.com/nomisoft/rtwv-map
config.js
var config = {}
// Port to run the application on
config.port = 3000;
// Log file format - either combined or common
config.logformat = 'combined';
// Directory of the log files to parse
config.logdir = '/Applications/XAMPP/xamppfiles/htdocs/logs/';
// Debugging mode outputs details to console - either true or false
config.debug = true;
module.exports = config;
frontend.js
$(document).ready(function() {
var routes = new Array();
var socket = io();
var currentWidth = $('#map').width();
var width = 938;
var height = 620;
var projection = d3.geo.mercator().scale(150).translate([width / 2, height / 1.41]);
var path = d3.geo.path().projection(projection);
var svg = d3.select("#map")
.append("svg")
.attr("preserveAspectRatio", "xMidYMid")
.attr("viewBox", "0 0 " + width + " " + height)
.attr("width", currentWidth)
.attr("height", currentWidth * height / width);
queue().defer(d3.json, "countries.json")
.await(function(error, countries) {
svg.append("g")
.attr("class", "countries")
.selectAll("path")
.data(topojson.feature(countries, countries.objects.countries).features)
.enter()
.append("path")
.attr("d", path);
});
socket.on('visitor', function(json){
$('#visits').append(
$('<tr>').append( $('<td>').text(json.visitor.ip) )
.append( $('<td>').text(json.status) )
.append( $('<td>').text(json.url) )
);
if( $('#visits').height() > $(window).height() ) {
$('#visits tbody tr:first').remove();
}
route = svg.append("path")
.datum({type: "LineString", coordinates: [ [json.visitor.geo[1],json.visitor.geo[0]], [json.server.geo[1],json.server.geo[0]] ]})
.attr("class", "route route-"+json.status)
.attr("d", path);
var totalLength = route.node().getTotalLength();
route.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(1000)
.ease("linear")
.attr("stroke-dashoffset", 0);
var key = routes.length;
routes[ key ] = route;
setTimeout(function(key) {
routes[key].style("opacity", 1).transition().duration(5000).style("opacity", 0).remove();
routes[key] = null;
}, 2000, key);
});
});
index.js
// Import config variables
var config = require('./config');
// Import Express framework
var app = require('express')();
// Import the http module
var http = require('http').Server(app);
// Import socket.io library
var io = require('socket.io')(http);
// Import GeoIP library for converting IP's to locations
var geoip = require('geoip-lite');
// Import os module for detecting network interfaces
var os = require('os');
// Import filesystem module
var fs = require('fs');
// Import child process module for running tail in a child process
var spawn = require('child_process').spawn;
io.set('origins', '*:*');
// Get the IP address of the server
var addresses = [];
var interfaces = os.networkInterfaces();
for(var k in interfaces) {
for(var k2 in interfaces[k]) {
var address = interfaces[k][k2];
if (address.family === 'IPv4' && !address.internal) {
addresses.push(address.address);
}
}
}
var tail;
// Array to hold list of files to tail
var logfiles = [];
// Loop through all the files in the given folder
fs.readdir(config.logdir, function(err, files) {
if( files instanceof Array ) {
files.forEach(function(filename){
if( config.debug ) {
console.log('Tailing ' + filename);
}
logfiles.push(config.logdir + filename);
});
// Tail all the files in our logfiles array
tail = spawn("tail", ["-f"].concat(logfiles));
} else {
console.log('No log files found');
}
});
// Request to load the homepage
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
// Request to load the countries json file
app.get('/countries.json', function(req, res){
res.sendFile(__dirname + '/countries.json');
});
// Request to load stylesheet
app.get('/style.css', function(req, res){
res.sendFile(__dirname + '/style.css');
});
// Request to front end javascript file
app.get('/frontend.js', function(req, res){
res.sendFile(__dirname + '/frontend.js');
});
// Bind function to io connection event
io.on('connection', function(socket){
// When a new line is found in the tailed files
tail.stdout.on("data", function (data) {
console.log('Connected to Socket.IO');
// For each new line
var lines = data.toString().split(/(r?n)/g);
lines.forEach(function(line) {
// Perform regular expression match on the new line
if( config.logformat == 'combined' ) {
var format = /^(S+) (S+) (S+) ([[^]]+]) ("[^"]+") (d+) (d+) ("[^"]*") ("[^"]*").*$/;
} else {
var format = /^(S+) (S+) (S+) ([[^]]+]) ("[^"]+") (d+) (d+)$/;
}
var visit = line.match(format);
if( visit != null && ( visit.length == 7 || visit.length == 10 ) ) {
console.log('new');
// Perform regular expression match on the request section of the log
var request = visit[5].match(/^"(GET|POST|OPTIONS|HEAD)+ (S+) HTTP/1.d+"$/);
// if request is to a page (not image/css/js etc)
var extension = request[2].match(/.([0-9a-z])+$/i);
var exclusions = ["jpg","gif","js","css","bmp","svg","exe","mp4","mpg","mov","ico"];
if( extension == null || exclusions.indexOf(extension[1]) == -1 ) {
// get lat/lng for ip address
var geo = geoip.lookup(visit[1]);
var server_geo = geoip.lookup(addresses[0]);
// Create json to output to the browser
var data = {
'status': visit[6],
'url': request[2],
'visitor': {
'ip': visit[1],
'geo': (geo != null && 'll' in geo) ? geo.ll : [0,0]
},
'server': {
'ip': addresses[0],
'geo': (server_geo != null && 'll' in server_geo) ? server_geo.ll : [0,0]
}
}
// Send data to the browser
io.emit('visitor', data);
if( config.debug ) {
console.log('Sending for '+line);
}
}
}
});
});
});
// Open a connection listening on chosen port
http.listen(config.port, function(){
if( config.debug ) {
console.log('listening on *:'+config.port);
}
});
index.html
<!doctype html>
<html>
<head>
<title>Real-Time Website Visitors Map</title>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="map"></div>
<table id="visits">
<thead>
<th>IP</th>
<th>Status</th>
<th>Request</th>
</thead>
<tbody>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://d3js.org/queue.v1.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script src="frontend.js"></script>
</body>
</html>
How can i solve the nextjs 14 rendering error?
I’m getting a rendering error from Nextjs 14, see the video below. I Don’t know what does it can do.
It happens when i do a soft refresh on my current page of the website: https://sergiorio.tech
- Go to the website
- Go to the contact page;
- Refresh the page
I uploaded my code on a gist, if you guys wanna checkout.

Gist: https://gist.github.com/Joaovsa7/947fb056df9b3eb2009b0d5aa83302ee
Operating System: Platform: darwin Arch: x64 Version: Darwin Kernel Version 22.6.0: Fri Sep 15 13:39:52 PDT 2023; root:xnu-8796.141.3.700.8~1/RELEASE_X86_64 Binaries: Node: 18.17.1 npm: 9.6.7 Yarn: 1.22.19 pnpm: N/A Relevant Packages: next: 14.0.3 eslint-config-next: 13.5.4 react: 18.2.0 react-dom: 18.2.0 typescript: 5.2.2 Next.js Config: output: N/A
i tried to refresh my page and i’m getting this error
Library for issuing “malicious” test API calls to rails app [closed]
What are some tools / patterns that are used to test whether a Rails app is vulnerable to modified Javascript code?
I am working on a Rails app that makes heavy use of JavaScript / API calls.
I’d like to write some end-to-end tests that verify that the API responds correctly if a user were to modify the Javascript and try to access other users’ data. For example, I want to verify that the API will return an error if the client requests an item that isn’t owned by the current user.
I’m using using the built-in Rails testing library. In principle, I just need to launch the server and make API calls. However, I’m not sure how to manage things like the session CSRF tokens. I assume there are well established libraries and techniques for this, but I don’t know what they are.
export ‘CreateBrowserRouter’ (imported as ‘CreateBrowserRouter’) was not found in ‘react-router-dom’ (possible exports: a big list)
I’m new to react programming I am traying to implement a router and I want to use CreateBrowserRouter() , but when I compile the project, the copiler tells me that the CreateBrowserRouter was not found in create-react-dom. What am I doing wrong? I am working on a windows PC with windows 11 pro on it (it if has anything to do). I am just trying to implement a simple navigation bar (navbar).
First of all , I am expecting the error the compiler shows to desapear, meaning that the CreateBrowserRuter was found in react-router-dom.
How can I get my random numbers into form? New to Javascript [closed]
Im trying to randomize 6 numbers, 1-30 into a form. I can get the random numbers but as far as putting them in the value of the form to submit I need some guidance.
Im trying to have the 6 random numbers post into the value auto and all the user has to do is submit. Im fairly new to this but Im a fast VISUAL learner
<!DOCTYPE html>
<html>
<body>
<h2>Random Lottery Number </h2>
<div id="1"></div><div id="2"></div><div id="3"></div><div id="4"></div><div id="5"></div><div id="6"></div>
<form action='process_lottery.phtml' method='post'>
<input type='hidden' name='_ref_ck' value='d5585c2025af1d9128bf0f27f0ad993a'>
<table width="301" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="middle" align="center" width="3"><img src="//images.neopets.com/images/blank.gif" width="1" height="50"></td>
<td valign="middle" align="center" width="50" background="/images/ball1.gif">
<input type='text' size=2 maxlength=2 name='one' value=''>
</td>
<td width="50" valign="middle" align="center" background="/images/ball2.gif">
<input type='text' size=2 maxlength=2 name='two'>
</td>
<td width="50" valign="middle" align="center" background="/images/ball3.gif">
<input type='text' size=2 maxlength=2 name='three'>
</td>
<td width="50" valign="middle" align="center" background="/images/ball4.gif">
<input type='text' size=2 maxlength=2 name='four'>
</td>
<td width="50" valign="middle" align="center" background="/images/ball5.gif">
<input type='text' size=2 maxlength=2 name='five'>
</td>
<td width="50" valign="middle" align="center" background="/images/ball6.gif">
<input type='text' size=2 maxlength=2 name='six'>
</td>
</tr>
</table><p>
<input type='submit' value='Buy a Lottery Ticket!'>
</form>
<script>
document.getElementById("1").innerHTML =
Math.floor(Math.random() * 30) + 1;
document.getElementById("2").innerHTML =
Math.floor(Math.random() * 30) + 1;
document.getElementById("3").innerHTML =
Math.floor(Math.random() * 30) + 1;
document.getElementById("4").innerHTML =
Math.floor(Math.random() * 30) + 1;
document.getElementById("5").innerHTML =
Math.floor(Math.random() * 30) + 1;
document.getElementById("6").innerHTML =
Math.floor(Math.random() * 30) + 1;
</script>
</body>
</html>
Im just trying to get the numbers to populate in the value, or form so I can submit
puppeteer-with-fingerprints browser not launching
i’m trying to work with puppeteer-with-fingerprints library but after successful download and installation it throws this error
reject(new Error(`Cannot connect to the WebSocket server (reason: ${error.reason})n${INVALID_ENGINE_ERROR}`));
^
Error: Cannot connect to the WebSocket server (reason: connection failed)
This could be due to the fact that the engine was not downloaded or unpacked correctly.
Try completely deleting the engine folder and restarting the code until it completes.
If this does not help, open an issue with a detailed description of the problem.
at C:UsersHABIBDesktopmax-autonode_modulesbas-remote-nodesrcservicessocket.js:53:18
at Timeout._onTimeout (C:UsersHABIBDesktopmax-autonode_moduleschnldistchannel.cjs.js:2:4848)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512:7)
Node.js v18.16.1
i have tried deleting the engine folder severally and rerun the code but it still always throws the same error.
i have the latest version of puppeteer installed and puppeteer-core also.
here is the code
/* With fingerprints */
const { plugin } = require('puppeteer-with-fingerprints');
const StealthPlugin = require("puppeteer-extra-plugin-stealth");
(async () => {
const fingerprint = await plugin.fetch('', {
tags: ['Microsoft Windows', 'Chrome'],
});
console.log('fingerprints featched')
plugin.useFingerprint(fingerprint);
plugin.use(require('puppeteer-extra-plugin-block-resources')({
blockedTypes: new Set(['image', 'stylesheet', 'media', 'font','others' ]),
}))
plugin.use(StealthPlugin)
console.log('passed all thr stages')
const browser = await plugin.launch({});
// The rest of the code is the same as for the standard `puppeteer` library:
const page = await browser.newPage();
await page.goto('https://browserleaks.com/canvas', { waitUntil: 'networkidle0' });
console.log('Canvas signature:', await page.$eval('#crc', (el) => el.innerText));
// await browser.close();
})();
Any help will be highly appreciated
