So I am trying to run some react code (simple search bar code) from my terminal. I put my source code within the App.jsx, the default made by “npx create-react-app”, however, anytime I run npm start, I only get the default React page telling me to “edit App.js and reload”. I ran my code within the sandbox environment within the react website and it was working fine. I am not entirely sure what I am doing wrong here. Any suggestions?
Category: javascript
Category Added in a WPeMatico Campaign
Facebook Login OAuth Flow without SDK
When I use the connect.facebook.net/en_US/sdk.js and call FB.login() I get a login/auth popup window. When someone logs in, the window closes, and the callback function supplied to FB.login is called with a response object. From that response object I pull out response.authResponse.accessToken and I can use that to verify user information by calling facebook. Great!
Now how do I do that without using the sdk.js?
I can manually open the popup and there is some documentation out in the wild on how to do that.
const appId = 'REDACTED';
const redirectUri = encodeURIComponent('https://example.net/callback');
// Construct the Facebook login URL
const loginUrl = `https://www.facebook.com/v19.0/dialog/oauth?client_id=${appId}&redirect_uri=${redirectUri}&response_type=token&scope=public_profile,email`;
// Open the Facebook login window
window.open(loginUrl, 'Facebook Login', 'width=600,height=400');
But now the flow is completely different! It uses a callback address and loads that address in the popup after login instead of closing. I don’t want that. Somehow or other the SDK opens the window and sets up messaging between the parent and the popup. How do I recreate that?
The end goal is to :
- Not have the js sdk loaded
- Have the facebook popup close on login
- Have the facebook popup call my own callback method and pass the token
Getting value from Props before making API call [duplicate]
Hey so I’m trying to take a user’s latitude and longitude and use that data in an API call to get accurate information.
I’m running into a problem where my API call is being sent before the State that includes the latitude and longitude are being updated. That means the api call is being sent with
`lat=undefined&long=undefined`
rather then
`lat=${latitude}$long=${longitude}`
I’m looking for a way to stop the useEffect from firing until the state is updated.
The state is being passed down as a prop from App.js
function App() {
let [latitude, setLatitude] = useState();
let [longitude, setLongitude] = useState();
let setLocation = () => {
if("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(e) {
setLatitude(e.coords.latitude.toFixed(3))
setLongitude(e.coords.longitude.toFixed(3))
})
} else {
setLatitude(-34)
setLongitude(174)
}
}
setLocation();
return (
<div className="App">
<Header location={{latitude, longitude}}/>
<Footer />
</div>
);
}
To Header.js
const Header = ({location}) => {
let [latitude, setLatitude] = useState(location.latitude);
let [longitude, setLongitude] = useState(location.longitude);
let [cityName, setCityName] = useState('nyet');
useEffect(() => {
axios.get(`https://us1.locationiq.com/v1/reverse?key=<apikey>&lat=${location.latitude}&lon=${location.longitude}&format=json`)
.then((res) => {
if('city' in res.data.address) {
setCityName(res.data.address.city)
} else if('county' in res.data.address) {
setCityName(res.data.address.county)
} else if('state' in res.data.address) {
setCityName(res.data.address.state)
} else if('country' in res.data.address) {
setCityName(res.data.address.country)
} else (
setCityName('')
)
})
.catch((err) =>
console.log(err)
)
}, [latitude, longitude])
return(
<>
<h1>{cityName} Weather</h1>
</>
)
}
This is where I’m at now,
I’ve tried a couple other things but haven’t been able to implement them properly, so hopefully someone here can help 🙂
Thanks in advance!
I’ve tried implementing a Promise or Async, but I’m just not sure how to properly do it with useEffect, etc.
Collection functions return not a function after working once
I have a project that uses Vue components and collection design pattern for list manipulation. Inside of the collection, I have an arr.add function that adds a new object to the list when a button is pressed. This works correctly the first time called but then shows an error stating it is not a function if it is called a second time. This is happening for all my function calls.
If I manually enter the data into the list and avoid using the collection call it works fine but if I use the collection for a second time I get the error: Uncaught TypeError: this.exerciseList.add is not a function
This is the collection model:
function ExerciseCollection(arr = []){
arr.add = function (exercise, date){
if (date){
exercise.date = date;
}
exercise.id = genId(date);
this.push(exercise);
return this;
}
arr.delete = function (exercise){
this.splice(this.indexOf(exercise), 1);
return this;
}
arr.deleteSet = function (exercise, set){
let editExercise = this.indexOf(exercise);
editExercise.weight.splice(set, 1);
editExercise.reps.splice(set, 1);
editExercise.sets--;
return this;
}
arr.addSet = function (exercise){
this.indexOf(exercise).sets++;
return this;
}
return arr;
}
This is where they are called:
const app = Vue.createApp({
// All data for the app, must return an object
data() {
return {
exerciseList: new ExerciseCollection().add({
id: 0, title: 'Bench Press', date: '2024-04-03',
sets: 2, reps: [10, 10], weight: [185, 185]
}),
dayList: new DayExerciseCollection(),
reviewList: new ReviewCollection(),
daysReview:{},
selectedEditExercise: {},
currentDay: ''
};
},
methods: {
addExercise(exercise, date){
this.exerciseList.add(exercise, date);
this.dayList.add(exercise, date);
},
...(rest of the file works properly but is pretty long wont put it in here)
How to secure Firestore Database when communicating between Mobile App, Web App, and Node js project?
I have a node js project that tracks data and writes to my Firestore database. The mobile app and web app read the data from the Firestore database and parse to make graphs, etc. Up to this point I haven’t really given the security much thought. I am looking at security rules and App Check. I am looking to have some rules that only the node js project, web app, and mobile app can read and write from the Firestore database. I am in unfamiliar territory and was wondering if anyone could give me some advice on which direction to go.
Currently my rules include:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read;
allow write: if request.auth.uid == uid;
}
}
}
This did not bode over well with my node js project. I got the error:
@firebase/firestore: Firestore (9.23.0): GrpcConnection RPC 'Write' stream 0x86b8ac80 error. Code: 7 Message: 7 PERMISSION_DENIED: Missing or insufficient permissions.
[FirebaseError: 7 PERMISSION_DENIED: Missing or insufficient permissions.] {
code: 'permission-denied',
customData: undefined,
toString: [Function (anonymous)]
}
While I can fix this error, I am not sure I am even going the correct direction. Thanks in advance for any help you can provide.
How can I run a callback provided to custom component via tag attribute? [duplicate]
I’m developing a custom component which simply extends HTMLElement. I give the user the ability to specify one to three callbacks as tag attributes.
<my-component onopen="callback1()" onclose="callback2()" onabort="callback3()"/>
I can easily get the attributes in the connectedCallback()and attributeChangedCallback() methods. However, once I retrieve a callback, it’s a simple string.
Let’s say I save the callback in the private property #cb_close Now I need to call it: this.#cb_close( inp.value );
How can I do this?
Mermaid 10 + Render + Click
I it possible to attack a global click handler when rendering a Mermaid chart in this manner
I don’t want add the click handlers to the markup, I want to add it as a global handler at the time that I initialize
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="flowchart" class="mm"></div>
<script>
window.element = document.querySelector('#flowchart');
window.clickFunction = function(nodeId) {
alert('Clicked on node ' + nodeId);
};
</script>
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
console.log(clickFunction)
mermaid.initialize({startOnLoad: false, securityLevel: 'loose', click: clickFunction});
document.addEventListener("DOMContentLoaded", async function () {
const drawDiagram = async function () {
const graphDefinition = 'graph TBna-->b;';
const { svg, bindFunctions } = await mermaid.render('graphDiv', graphDefinition);
element.innerHTML = svg;
// This can also be written as `bindFunctions?.(element);` using the `?` shorthand.
console.log(bindFunctions)
if (bindFunctions) {
bindFunctions(element);
}
};
drawDiagram();
});
</script>
</body>
</html>
Prisma batch updating query type eror on Typescript project,
I’m building a chat service api with tyepscript and prisma. but I couldn’t fix one of my batch updating queries.
the query is when a user deletes account, it’s channels and groups get deleted as well as the members. and also for every subscribed user’s, it should remove from the list of subscribed groups and channels. but I’ve got an error query trying to do so
here’s the query, (which I’m getting error at)
await db.user.updateMany({
where: {
OR: [
{
channels: {
some: {
id: {
in: listOfDeletedChannels,
},
},
},
},
{
groups: {
some: {
id: {
in: listOfDeletedGroups,
},
},
},
},
],
},
data: {
channels: { //I'm getting an error on this
disconnect: {
id: {
in: listOfDeletedChannels,
},
},
},
groups: { // And this
disconnect: {
id: {
in: listOfDeletedGroups,
},
},
},
},
});
my editor is showing me this error
Object literal may only specify known properties, and 'channels' does not exist in type '(Without<UserUpdateManyMutationInput, UserUncheckedUpdateManyInput> & UserUncheckedUpdateManyInput) | (Without<...> & UserUpdateManyMutationInput)'.ts(2353)
index.d.ts(2213, 5): The expected type comes from property 'data' which is declared here on type '{ data: (Without<UserUpdateManyMutationInput, UserUncheckedUpdateManyInput> & UserUncheckedUpdateManyInput) | (Without<...> & UserUpdateManyMutationInput); where?: UserWhereInput | undefined; }'
here’s the shema model
// schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(uuid())
email String @unique
username String @unique
name String
image String?
bio String?
password String
createdAt DateTime @default(now())
groups Group[] @relation("GroupMembers")
ownGroups Group[] @relation("GroupOwner")
channels Channel[] @relation("ChannelMembers")
ownChannels Channel[] @relation("ChannelOwner")
sentMessages Message[] @relation("UserSent")
recMessages Message[] @relation("UserRec")
contacts User[] @relation("Contact")
contactOf User[] @relation("Contact")
}
model Group {
id String @id @default(uuid())
username String @unique
name String
image String?
desc String?
members User[] @relation("GroupMembers")
owner User @relation("GroupOwner", fields: [ownerId], references: [id])
ownerId String
messages Message[] @relation("GroupRec")
}
model Channel {
id String @id @default(uuid())
username String @unique
name String
image String?
desc String?
members User[] @relation("ChannelMembers")
owner User @relation("ChannelOwner", fields: [ownerId], references: [id])
ownerId String
messages Message[] @relation("ChannelSent")
}
model Message {
id String @id @default(uuid())
text String?
images String[]
emoji String?
createdAt DateTime @default(now())
userSender User? @relation("UserSent", fields: [userSenderId], references: [id])
userSenderId String?
userRec User? @relation("UserRec", fields: [userRecId], references: [id])
userRecId String?
groupRec Group? @relation("GroupRec", fields: [groupRecId], references: [id])
groupRecId String?
chanSender Channel? @relation("ChannelSent", fields: [chanSenderId], references: [id])
chanSenderId String?
@@index([userRecId], name: "user_receiver_index")
@@index([groupRecId], name: "group_receiver_index")
@@index([userSenderId], name: "user_sender_index")
@@index([chanSenderId], name: "channel_sender_index")
}
I was trying to delete a user, then it’s channels and groups, also remove the deleted channels and groups from the user’s subscription list
Page on reactjs not displaying, coded with javascript
I am currently working on a project with javascript on react but i cannot get the Suggestions page to display what I coded.
<button type="submit" class="btn btn-primary"><Link to = "/suggest" className='nav-link'>Submit</Link></button>
i have this button on the previous code that takes me to the suggestions page, when I click the button, it does go to the suggestions page but the problem is that it does not display anything but the header for the page. How do I fix this?
this is what I have on the suggestions page:
` import React from ‘react’;
import ‘./ComputerList.scss’;
const ComputerList = () => {
return (
<div className="container mt-100">
<div className="row">
<div className="col-md-4 col-sm-6">
<div className="card mb-30">
<div className="card-body text-center">
<h4 className="card-title">Test Computer</h4>
<p className="text-muted">Lorem ipsum dolor sit amet</p>
<p>Model: Test Model</p>
<p>SKU: 123456</p>
<div className="actions">
<button>Compare</button>
<button>Save</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default ComputerList;`
How to find out where y intersects with x on the surface of a cycloid?
To find out where y intersect with x on the surface of the circle i use Math.sqrt(radius * radius - Math.pow( x, 2)) .
How do I find out where y intersects with x on the surface of a cycloid?
In the snippets bellow I have a circle and a cycloid. For the circle you can see I am able to get the value of y from x. I want to be able to do the same for the cycloid.
(() => {
const inputX = document.getElementById('xCircle')
inputX.addEventListener('input', (e) => {
const x = e.target.value
ctx.clearRect(0, 0, radius, radius)
drawCurve()
drawIntersection(x)
})
const radius = 200
const canvas = document.getElementById('circle')
canvas.width = radius
canvas.height = radius
const ctx = canvas.getContext('2d')
const drawCurve = () => {
ctx.beginPath()
ctx.arc(radius, 0, radius, 0, Math.PI * 2)
ctx.stroke()
}
drawCurve()
const drawIntersection = (x) => {
const y = Math.sqrt(radius * radius - Math.pow(radius - x, 2))
ctx.beginPath()
ctx.moveTo(x, radius)
ctx.lineTo(x, y)
ctx.lineTo(radius, y)
ctx.stroke()
}
drawIntersection(inputX.value)
})();
(() => {
const inputX = document.getElementById('xCycloid')
inputX.addEventListener('input', (e) => {
const x = e.target.value
ctx.clearRect(0, 0, canvasW, canvasH)
drawCurve()
drawIntersection(x)
})
const radius = 100
const canvas = document.getElementById('cycloid')
const canvasW = radius * Math.PI, canvasH = radius * 2
canvas.width = canvasW
canvas.height = canvasH
const ctx = canvas.getContext('2d')
const drawCurve = () => {
ctx.beginPath()
for (let t = 0; t <= Math.PI; t += 0.01) {
const x = radius * (t - Math.sin(t))
const y = radius * (1 - Math.cos(t))
ctx.lineTo(x, y)
}
ctx.stroke()
}
drawCurve()
const drawIntersection = (x) => {
const y = 0
ctx.beginPath()
ctx.moveTo(x, canvasH)
ctx.lineTo(x, y)
ctx.lineTo(canvasW, y)
ctx.stroke()
}
drawIntersection(inputX.value)
})();
canvas {
border: 1px solid
}
<canvas id="circle"></canvas>
<form>
<label><input id="xCircle" type="number" value="30"></label>
</form>
<br>
<canvas id="cycloid"></canvas>
<form>
<label><input id="xCycloid" type="number" value="40"></label>
</form>
How to find which script is making changes to entered creditions and making a payload from it?
enter image description hereAt “”https://dashboard.ngrok.com/login”” this website , for example if you enter ‘[email protected]’ as email and ‘test’ as password and after hitting login button , the payload will not be the same as you enterd and it will be like this :
https://postimg.cc/WqMnGyMt
(see the picture)
how to know that which script make changes to this information and simulte that?
I understood that if you change the len of password or email , those characters would change to different characters.
list inside where UL is given position: absolute and is given position: relative rendered in a dialog, Can’t scroll to end of dialog
NAV
position: relative
ul
position: absolute
should scroll to end of dialog
Javacript code not working without console of developer tools of browser
I am working on a .Net razor pages web app. The web app has an authentication system in it when the authentication system validates the user the user goes to the index page of the user end of the website but the user can navigate back to the previous(login) page. I wanted that when the user wants to go back to the previous page the system automatically triggers a button which is coded in _layout.cshtml file. I have coded a javascript code but that code only works if the console of developer tools of the browser is open can anyone please tell me what is wrong with my javascript code??
Following is the javascript code:
@section Scripts {
<script>
window.history.pushState(null, "", window.location.href);
var logoutButton = document.getElementById('logoutButton');
window.onpopstate = function () {
window.history.pushState(null, "", window.location.href);
logoutButton.click();
};
</script>
}
Please fix the error of the code I have explained
When I click on the edit button, I want the editing table at the bottom of the page to open, but somehow it does not appear
When I click on the edit button, I want the editing table at the bottom of the page to open, but somehow it does not appear.
display:none When I deleteit, the table below appears, but I want it to appear when I click the button.
echo '<td>'; echo '<button class="updateBtn" onclick="toggleUpdateForm(' . $row['id'] . ')">'; echo '<i class="fa-solid fa-pen" style="color: #0a0a0a;"></i>'; echo '</button>';
<!-- Güncelleme Formu -->
<div class="container" style="display:none;" id="updateFormContainer">
<div class="col-md-3">
<div class="update-form p-3">
<h2>Veri Güncelle</h2>
<form id="updateForm" action="guncelle.php" method="post">
<input type="hidden" id="updateId" name="id">
<div class="mb-3">
<label for="updateName" class="form-label">First:</label>
<input type="text" class="form-control" id="updateName" name="name">
</div>
<div class="mb-3">
<label for="updateDate" class="form-label">Date Created:</label>
<input type="text" class="form-control" id="updateDate" name="date">
</div>
<div class="mb-3">
<label for="updateRole" class="form-label">Role:</label>
<select class="form-select" id="updateRole" name="role">
<option value="Admin">Admin</option>
<option value="Publisher">Publisher</option>
<option value="Modaratör">Modaratör</option>
<option value="Tester">Tester</option>
</select>
</div>
<div class="mb-3">
<label for="updateStatus" class="form-label">Status:</label>
<select class="form-select" id="updateStatus" name="status">
<option value="Inactive">İnaktif</option>
<option value="Idle">Boşta</option>
<option value="Active">Aktif</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Güncelle</button>
<button type="button" class="btn btn-secondary" onclick="cancelUpdate()">İptal</button>
</form>
</div>
</div>
</div>
function toggleUpdateForm(id) {
var updateFormContainer = document.getElementById('updateFormContainer');
var updateIdField = document.getElementById('updateId');
var updateFormDisplay = window.getComputedStyle(updateFormContainer).display;
// Eğer güncelleme formu zaten görünürse ve güncellenen ID aynı ise, iptal edilmiş gibi kabul edip formu gizle
if (updateFormDisplay === 'block' && updateIdField.value === id) {
updateFormContainer.style.display = 'none';
} else {
// Formu doldur
var row = document.querySelector('tr:nth-child(' + (id + 1) + ')');
var cells = row.querySelectorAll('td');
updateIdField.value = id;
document.getElementById('updateName').value = cells[1].innerText;
document.getElementById('updateDate').value = cells[2].innerText;
document.getElementById('updateRole').value = cells[3].innerText;
document.getElementById('updateStatus').value = cells[4].innerText;
// Formu göster
updateFormContainer.style.display = 'block';
}
}
When I run the API in the browser, I get the data correctly. However, when I add it to the frontend, it shows this error
When I check the network headers, if I search for the API directly in the browser, it shows Content-Type: application/json, but when I check on the frontend of the website, it shows Content-Type: text/html; charset=utf-8.
“error”
⨯ SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
“code”
const URL = `${process.env.NEXT_PUBLIC_API_URL}/categories`;
console.log("Constructed URL:", URL)
const getCategories = async (): Promise<Category[]> => {
const res = await fetch(URL, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},);
return res.json();
}