i am implementing a dApp using react js and web3.js i have implemented the metamask login but i want to have a button logout which logout the metamask account from the application , i have tried to install wagmi and rainbowkit libraries to acheive the metamask logout , but i had a mismatch conflicts between typescript version my app uses and the version these libraries use and dependencies conflict .
So what is the solution to logout metamask using a button from my app and are there any other libraries to do that ? Thank you .
Category: javascript
Category Added in a WPeMatico Campaign
unshift vs assigning the values with loop vs manually assigning values by hand. Which one is faster?
For javascript which one is faster?
a.unshift("new first value");
vs
for(i=a.length; i>0; i--) a[i] = a[i-1];
a[0] = "new first value";
vs
a[5] = a[4];
a[4] = a[3];
a[3] = a[2];
a[2] = a[1];
a[1] = a[0];
a[0] = "new first value";
Well, of course, assigning values by hand is unpractical.
But there would be cases that your array has very few items that you can assign it with your hand and it’s in a loop that would repeat it millions of times.
So I just included it.
Then the main question is:
- Is there any performance difference between first two cases?
- And can third one be faster than both of them when
React and Stripe integration – client secret returned by Stripe not being recognised by React
I’m integrating Stripe in to my React SPA
I’ver created a Checkout component in my front end:
export default function Checkout() {
const fetchClientSecret = useCallback(() => {
// Create a Checkout Session
fetch("/create-checkout-session", {
method: "POST",
})
.then((res) => res.json())
.then((data) => data.clientSecret);
}, []);
// Define options being passed to Stripe
const options = {fetchClientSecret};
return (
<div>
<EmbeddedCheckoutProvider stripe={stripePromise} options={options}>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
</div>
);
}
and a corresponding create-checkout-session endpoint in my Express back end
app.post('/create-checkout-session', async (req, res) => {
const session = await stripe.checkout.sessions.create({
ui_mode: 'embedded',
line_items: [
{
price: 'price_1Oxtf42MrIfdvsrao10PzNxF',
quantity: 1,
},
],
mode: 'payment',
return_url: `${YOUR_DOMAIN}/thankyou?session_id={CHECKOUT_SESSION_ID}`,
});
console.log(session.client_secret);
res.send({clientSecret: session.client_secret});
});
The price ID I’m passing to stripe.checkout.sessions.create is correct. My console.log call confirms that the client secret is being correctly generated by the back end.
My problem is that Stripe is returning this when I call the Checkout conpionent:
Uncaught (in promise) IntegrationError: fetchClientSecret failed with error "The fetchClientSecret function should always resolve with a client secret as a string. The function that was provided resolved with a value type of undefined."
Can anyone help explain why this is happening, please?
split loaded html into 2 lines
I am loading in the content from the backend like so:
<td>{{ data.website_code_integration }}</td>
and the output is as follows:
<script src="127.0.0.1:5000/bot.js" api-key="xxx"></script><div id="bot"></div>
what I would like to do is actually split it up so the output looks like this on the page:
<script src="127.0.0.1:5000/bot.js" api-key="xxx"></script>
<div id="bot"></div>
I have tried this:
window.addEventListener('DOMContentLoaded', (event) => {
setTimeout(() => {
let div = document.getElementById('bot');
if (div) {
div.style.display = 'block';
}
}, 1000);
});
but it doesn’t work. any suggestions?
Unable to Playback MediaRecorder Blobs Streamed over WebSocket
I am unable to get blobs recorded by an instance of MediaRecorder that are sent over WebSocket to playback on the client machine’s video element. Here is an excerpt of my code:
sender.js:
navigator.getUserMedia({
video: {
facingMode: 'user'
},
audio = true
}).then(stream => {
const recorder = new MediaRecorder(stream);
recorder.ondataavailable(event => {
socket.send(event.data); // according to the client console, THIS SENDS A BLOB!!!
});
recorder.start(1000);
});
receiver.js:
socket.onmessage = (message) => {
console.log(message.data); // instanceof Blob
blob = message.data;
blob = new Blob([message.data], { // the Blob.type attribute is ignored when sent by WebSocket: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
type: 'video/webm; codecs=vp9'
});
// blob = blob.slice(0, blob.size, 'video/webm; codecs=vp9'); // this answer does not work: https://stackoverflow.com/a/50875615/1079320
video.srcObject = blob; // under "Usage notes" from https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject the URL.createObjectUrl() method is no longer needed!
video.play(); // const video = document.getElementById('video-element-id');
};
I get no errors, but the video element simply does not play. Testing using the Firefox browser.
How would I synchronize a multiplayer pong game for all players in firebase realtime database?
I’ve been working on a simple multiplayer pong game for the browser using javascript but can’t for the life of me figure out how to start the game for all players without everything getting desynced.
gif of the ball on both players sides not being synced
I really do not want to save the balls’ position every millisecond to firebase as it would probably just be inefficient and waste space.
I did however sync up the players movements by saving their corresponding Y value to firebase and that works fine.
I am hosting this on github pages so I cannot use something like socket.io or websockets for this (atleast I think I can’t) so I am resorting to firebase.
I have tried setting a ‘ready’ boolean to each player after they have loaded the pong game and only starting it once both players are ready but that still doesn’t work to sync the ball up.
Here is my code that handles multiplayer and the pong game, anything below //GAME CODE is pong, anything above is firebase related
function handleMultiplayer(gameref) {
const ready = ref(database, "public/ongoingGames/pong/" + gameref.key + "/players/plr" + currentPlayer + "/ready")
const yRef = ref(database, "public/ongoingGames/pong/" + gameref.key + "/players/plr" + currentPlayer + "/y")
const otherPlayer = currentPlayer === 1 ? 2 : 1
const otherPlayerYRef = ref(database, "public/ongoingGames/pong/" + gameref.key + "/players/plr" + otherPlayer + "/y")
const otherPlayerReadyRef = ref(database, "public/ongoingGames/pong/" + gameref.key + "/players/plr" + otherPlayer + "/ready")
let interval = setInterval(() => {
if (currentPlayer == 1) {
set(yRef, player1Y)
}
if (currentPlayer == 2) {
set(yRef, player2Y)
}
}, 10);
onDisconnect(gameref).remove().then(() => {
//stops it spamming the yref
clearInterval(interval)
})
//when the other player moves up or down set their current Y value in game
onValue(otherPlayerYRef, snapshot => {
const data = snapshot.val()
if (otherPlayer === 1) {
player1Y = data
}
if (otherPlayer === 2) {
player2Y = data
}
})
let currentPlayerReady
onValue(gameref, (snapshot) => {
const data = snapshot.val()
if (!data) { location.reload() }
// if 2 players are in the game, start it and make the canvas visible
if (Object.keys(data.players).length == maxPlayers) {
// this only triggers once as shown by the if statement
if (canvas.style.display != "flex") {
canvas.style.display = "flex"
matchmaking.remove()
document.getElementById("canvasContainer").style.display = "block"
document.getElementById("name1").textContent = data.players.plr1.name + " score : "
document.getElementById("name2").textContent = data.players.plr2.name + " score : "
//delay to make sure the player has loaded in
setTimeout(() => {
set(ready, true)
currentPlayerReady = true
}, 2000);
setInterval(interval)
}
}
})
// wait for condition to turn true
function waitFor(conditionFunction) {
const poll = resolve => {
if (conditionFunction()) resolve();
else setTimeout(_ => poll(resolve), 400);
}
return new Promise(poll);
}
// trigger once the other players ready value has changed
onValue(otherPlayerReadyRef, async (snapshot) => {
const otherPlayerReady = snapshot.val()
console.log("A")
await waitFor(_ => currentPlayerReady === true)
await waitFor(_ => otherPlayerReady === true)
//calls when both players are ready, starts game
console.log("B")
//GAME CODE
// i'll be honest I used AI to generate the code below this comment as a test for multiplayer, it works fine
let dx = 2;
let dy = -2;
let player1UpPressed = false;
let player1DownPressed = false;
let player2UpPressed = false;
let player2DownPressed = false;
let player1Score = 0;
let player2Score = 0;
function drawPaddle(y1, y2) {
ctx.fillStyle = '#000'; // Set fill style for paddles
ctx.fillRect(0, y1, paddleWidth, paddleHeight); // Draw paddle for player 1
ctx.fillRect(canvas.width - paddleWidth, y2, paddleWidth, paddleHeight); // Draw paddle for player 2
}
function drawBall() {
ctx.beginPath();
ctx.arc(ballX, ballY, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
function drawScores() {
let player1Text = document.getElementById("name1").textContent;
let player2Text = document.getElementById("name2").textContent;
// Extract the player names
let playerName1 = player1Text.substring(0, player1Text.indexOf(':') + 1);
let playerName2 = player2Text.substring(0, player2Text.indexOf(':') + 1);
// Update only the score values
document.getElementById("name1").textContent = playerName1 + " " + player1Score;
document.getElementById("name2").textContent = playerName2 + " " + player2Score;
}
function updatePaddlePositions() {
if (currentPlayer === 1) {
if (player1UpPressed && player1Y > 0) {
player1Y -= 5;
}
if (player1DownPressed && player1Y < canvas.height - paddleHeight) {
player1Y += 5;
}
} else if (currentPlayer === 2) {
if (player2UpPressed && player2Y > 0) {
player2Y -= 5;
}
if (player2DownPressed && player2Y < canvas.height - paddleHeight) {
player2Y += 5;
}
}
}
function updateScores() {
// Check if the ball went past the paddles
if (ballX - ballRadius <= 0) {
player2Score++; // Player 2 scored
resetBall();
} else if (ballX + ballRadius >= canvas.width) {
player1Score++; // Player 1 scored
resetBall();
}
}
function resetBall() {
ballX = canvas.width / 2;
ballY = canvas.height / 2;
dx = -dx; // Change ball direction
}
function draw() {
// Draw trail effect by filling canvas with transparent color
ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw paddles and ball
drawPaddle(player1Y, player2Y);
drawBall();
drawScores(); // Draw scores
// Bounce the ball off the walls
if (ballY + dy > canvas.height - ballRadius || ballY + dy < ballRadius) {
dy = -dy;
}
// Bounce the ball off the paddles
if (
(ballX - ballRadius <= paddleWidth && ballY >= player1Y && ballY <= player1Y + paddleHeight) ||
(ballX + ballRadius >= canvas.width - paddleWidth && ballY >= player2Y && ballY <= player2Y + paddleHeight)
) {
dx = -dx;
}
// Update ball position
ballX += dx;
ballY += dy;
// Update paddle positions
updatePaddlePositions();
// Update scores
updateScores();
}
document.addEventListener('keydown', function (e) {
if (e.key === 'w') {
if (currentPlayer === 1) {
player1UpPressed = true;
} else if (currentPlayer === 2) {
player2UpPressed = true;
}
} else if (e.key === 's') {
if (currentPlayer === 1) {
player1DownPressed = true;
} else if (currentPlayer === 2) {
player2DownPressed = true;
}
}
});
document.addEventListener('keyup', function (e) {
if (e.key === 'w') {
if (currentPlayer === 1) {
player1UpPressed = false;
} else if (currentPlayer === 2) {
player2UpPressed = false;
}
} else if (e.key === 's') {
if (currentPlayer === 1) {
player1DownPressed = false;
} else if (currentPlayer === 2) {
player2DownPressed = false;
}
}
});
setInterval(draw, 10);
})
}
Ionic 7+ Angular LoadingController with Http Interceptor Loader Present and Dismiss issue
Issue Description:
I’m encountering an issue with the LoadingController in Ionic 7 when used in conjunction with an HttpInterceptor. The LoadingController is not being presented or dismissed correctly in certain scenarios.
Steps to Reproduce:
With this logic in interceptor and with 2 call Api you will see the error that the loading dose’t dismiss correctly
The loading spinner should be dismissed when the HTTP request completes or encounters an error.
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class LoaderInterceptor implements HttpInterceptor {
private loading: boolean = false;
constructor(
private loadingController: LoadingController,
private readonly translateService: TranslateService
) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.presentLoading();
return next.handle(req).pipe(
tap(
(event: HttpEvent<any>) => {
this.dismissLoading();
},
(err: any) => {
this.dismissLoading();
}
)
);
}
private async presentLoading() {
if (!this.loading) {
this.loading = true
const load = await this.loadingController.create({
message: this.translateService.instant("LOADING")
});
await load.present();
}
}
private async dismissLoading() {
if (this.loading) {
this.loading = false;
await this.loadingController.dismiss();
}
}
}
How can I convert an arbitrarily deep nested object to a similarly nested Map?
I am trying to convert an arbitrarily deep nested object to a similarly nested Map.
const exampleInput = { a: 1, b: { c: 2, d: { e: 3 } } };
const expectedOutput = new Map([['a', 1], ['b', new Map([['c', 2], ['d', new Map([['e', 3]])]])]]);
const nestedObj2Map = (o, m = new Map()) => {
for (const [k, v] of Object.entries(o)) {
if (typeof (v) === 'object' && v !== null) {
m.set(k, nestedObj2Map(v, m));
} else m.set(k, v);
}
return m;
};
nestedObj2Map(exampleInput);
When I run it in Chrome console, it returns a nested Map with too many entries. Can anyone see a way to achieve this goal?
node js crashing, saying a variable is undefined, when it isnt
here is my GET request, to render a page:
app.get("/:band", async (req, res) => {
const page = req.params.band;
try {
const result = await db.query("SELECT * FROM artists");
const artistData = result.rows;
const band = artistData.findIndex((info) => info.onewordid === page);
const bandInfo = artistData[band];
console.log(bandInfo);
const articlesresult = await db.query("SELECT * FROM articles WHERE artist_id = $1",
[bandInfo.id]);
res.render("artistpage.ejs", {
artistinfo: bandInfo,
data: artistData,
articles: articlesresult.rows,
});
} catch(err){
console.log(err)
}
});
{
id: 1,
name: ‘The Rolling Stones’,
picadress: ‘backgroundpic2.jpeg’,
onewordid: ‘stones’
}
undefined
TypeError: Cannot read properties of undefined (reading ‘id’)
at file:///Users/admin/Downloads/Web%20development%20Project/Backend/Blog%20Project%20Styling/index.js:83:15
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
`
why can I console log this, but I get bandInfo.id as "undefined"?
PS sorry for messy code
signalr 2.4.2: internet or wifi connected clients don’t receive broadcasts. – mostly
Man this is wierd. (or wired :-))
I have a 2008 r2 server with local clients connected via ethernet wire that are able to generate signalr boardcasts and both recieve the broadcast themselves but also as expected send them to other local wired connected clients and have then recieved.
However, wifi connected clients in the same room can generate the broadcast but never receive them (javascript function not called) and internet connected clients behave the same way, they can generate the broadcast but never receive it. Moreover the internet / wifi clients never get the broadcasted events generated from the wired clients but all the wired clients including the one that generated it work.
Once in a blue moon one of these problem child clients will actually work. Like once in a week, and will continue to until the browser is refreshed (F5) then it’s game over again. I havent posted code because if you’ve seen one signalr implementation, you have seen them all, but if you want to see somthing I’ll post it.
My wife’s M2 MAC on wifi works – as if to taunt, but her IPad does not. My dev machine windows 7 does not work over wifi but does on the local iis, but a windows 10 laptop we have here in the house – won’t. All chrome: mvc webapp.
This is just nuts.
Targeting .Net 4.7.2 fwiw.
I have googled for weeks. I seem to be the only poor sole with this problem with a product that I have used with glee until I discovered this issue.
How to load a pdf form in browser and save it in React js? [closed]
How read a pdf form and show in browser in a iframe , user can fill the details and save/download in his system, a pdf template can be any type of form.
Unable make Radio button yes or no from pdf renderer?
enter image description here
Callback function using closure in javascript
I am trying to understand how closure is used in callback function in javascript.Can anybody explain me in detail ?
function fetchData(url, callback) {
fetch(url)
.then((response) => response.json())
.then((data) => callback(data))
.catch((error) => console.error(error));
}
//callback
function processData(data) {
console.log(data);
}
fetchData("https://jsonplaceholder.typicode.com/todos/1", processData);
Output:
Explanation:
The callback function 'processData()' has access to the data variable in its outer scope,
which is the result of the fetchData function.
As callbacks behave as if they are actually placed inside that
function, they are in practice closures: they can access the
containing function’s variables and parameters, and even
the variables from the global scope.
Another Example:
var processData = function (msg, callback) {
console.log("Doing some tasks");
callback(msg);
};
var myCallback = function (myMsg) {
console.log(myMsg);
};
processData("hello", myCallback);
processData("world", myCallback);
Output:
Doing some tasks
hello
Doing some tasks
world
Explanation: we have created a simple 'myCallback()' function in outer scope.
we are passing it to processData() function as a callback (function as parameter).
In 'processData()' function calls 'callback()' function,assuming 'callback()'
defined inside it as inner function it get access to 'msg' variable due to closure.
I tried reading different articles online,but i am not satisfied with there explanation about it.
login with nextjs and laravel
The backend of my site is written with Laravel. When I try with postman, everything is correct and I see the entered user information, but with next js, after entering the site (Auth::attempt(…)), the result is true, but I can’t see user information.
Even a cookie is set, but auth()->user() always returns null. And I also use sanctum Laravel package
component axios
import axios from 'axios';
export default axios.create({
baseURL: 'http://api.lanext.test',
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
withCredentials: true
});
component useAuth
import useSWR from "swr";
import axios from '@/lib/axios'
import { useRouter } from "next/navigation";
export default function useAuth({} = {}) {
const router = useRouter()
const { data: user, error, mutate } = useSWR('/api/v1/admin',
() => axios.get('/api/v1/admin').then(response => console.log(response.data.data, "ok"))
)
const csrf = () => axios.get('/sanctum/csrf-cookie')
const login = async ({ setErrors, ...props }) => {
axios.post('/api/v1/login', props)
.then(
() => mutate && router.push('/')
)
.catch(
error => {
console.log(error)
// if (error?.response?.status !== 422) throw error
// setErrors(Object.values(error.response.data.errors).flat())
}
)
}
return {
user,
csrf,
login
}
}
component login
const [submitting, setSubmitting] = useState(false);
const {login} = useAuth();
const handleSubmit = async (values, actions) => {
setSubmitting(true);
await login(values)
setSubmitting(false);
};
user component = It always returns null
const { user } = useAuth();
Must the fetch method request correspond to the server side http method
So I’m currently creating a login/signup prompt.
The signup prompt works perfectly fine and the client and server communicate just fine.
However the login prompt responds surprisingly different with a 400 of bad request if I set the method to ‘post’
await fetch('http://localhost:4500/users/Login',{
method:"POST",
headers:{
'Content-Type':'Application/json'
},
body:JSON.stringify(details)
})
And when I set it to ‘get’, of course it will fail since you can’t have a body property to a get method.
So with this I’m currently wondering If the fetch method has to correspond to the server http method or I’m just doing something wrong.
Here’s both the client and server code.
To add on, it doesn’t even call the api so I can’t get the log message(‘Got called ….’)
Client:
await fetch('http://localhost:4500/users/Login',{
method:"POST",
headers:{
'Content-type':'Application/json'
},
body:JSON.stringify(details)
})
//Same thing as above
Server:
router.post('/',passport.authenticate("local"),(request,response) => {
console.log("Got Called in login")
response.send(request.session.user)
})
Here’s the passport strategy I’m using:
module.exports = passport.use(
new Strategy(async (email,password,done) => {
try{
const userFinder = await Database.findOne({email:email})
if(userFinder && bcrypt.compareSync(password,userFinder.password)){
done(null,userFinder)
}
else throw new Error("Incorrect user Credentials")
}
catch(error){
console.log(error)
done(error,null)
}
})
)
Thank you for your time
In NextJS, how can I show a blob of type ‘image/jpeg’, received from an API call, on screen?
In nextjs, I do the following API call:
const response = await fetch('/api/generateimageHG2');
this call the following function:
import { HfInference } from "@huggingface/inference";
export default async function generate (req, res) {
try{
const inference = new HfInference('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');
const response = await inference.textToImage({
model: "stabilityai/stable-diffusion-2",
inputs: "award winning high resolution photo of a giant dragon/((ladybird)) hybrid, [trending on artstation]",
parameters: {
negative_prompt: "blurry",
},
});
console.log (response);
res.status(200).send(response);
} catch (error) {
throw new Error('Error fetching property information: ' + error.message);
}
};
The console log prints the following:
Blob { size: 93803, type: ‘image/jpeg’ }
So I know I’m getting a blob.
I’m really stuck in turning this blob into an image on the screen. I tried URL.CreateObjectURL, but that causes an error.
Anyone has any ideas?