When the user changes the button onClick again executes - javascript

When I have not yet signed in and I click the button : it gives alert to login first
And after that as soon as I login with google (via firebase auth) then the script again executes and this time it executes as logged in function and pushes me to another page...
<Button
key={q}
id={q}
onClick={handleClick}
>
some Text
</Button>
And here is handleClick function:-
const handleClick = (e) => {
e.preventDefault();
let name = e.target.offsetParent.id;
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
history.push("/testPage/" + btoa(name));
}else{
window.alert("Login To Continue");
}
});
};
Before signing in when I click the button the else statement executes... but as soon as I sign in then without clicking any button the if statement executes.
How do I remove the second execution i.e. once I click the button it gives me response and after I login, it should not again give me a response untill I again click it.

You are subscribing to an observable. Every time the observable fires your observer is called. You can store the subscription returned by the function to unsubscribe. Or you could just not subscribe to an observable and use the property:
const handleClick = (e) => {
e.preventDefault();
let name = e.target.offsetParent.id;
const user = firebase.auth().currentUser;
if (user) {
history.push("/testPage/" + btoa(name));
}else{
window.alert("Login To Continue");
}
};

Related

How Can I set OnClick for the Ok button in Alert Box?

I am Creating A systemtimeout functionality for my MERN App. I tried using React-idle-timer but unfortunately, it did not work. If someone can help me with that then it will be great too.
I tried another way to dislplay an alert box after a certain time. I want to create an OnClick for the OK button in the alert box.
it means after the alert box will be displayed when user will click on OK button it should run Logout Function and redirect user to the login page.
Here is the code for useTimeout.jsx and I am calling Alert box in App.js Also I am adding Logout funcion whcih I want to add as Onclick of okay button
useTimeout.jsx
import {useRef, useEffect} from 'react';
export default function useTimeout(callback, delay){
const stableCallback = useRef(callback);
useEffect(() =>{
stableCallback.current = callback;
}, [callback]);
useEffect(()=>{
const tick = () => stableCallback.current();
if (typeof delay !== 'number') return;
const t = setTimeout(tick, delay);
return ()=> clearTimeout(t);
}, [delay]);
}
This is how I have called it in App.js
import useTimeout from "./components/reactidealtimer/useTimeout";
function App() {
const { user } = useContext(AuthContext);
useTimeout(()=> alert("Session Timed Out"), 10000);
return (
Here is the logout Function which I want to add
function logout(){
localStorage.clear();
window.location.href = '/login';
};

"else" statement keeps triggering upon updating Firebase user's name?

I have a pop up modal which appears when the user clicks on "update profile" from the dropdown nav menu. In this modal, they can change their username.
I am trying to implement the following workflow: user clicks "update profile", types in their new username, clicks the "submit" button, the form resets and the modal closes.
The first username update works exactly as I want. Subsequent update attempts seem to trigger my "else" statement, which is to catch if the user left the new username field empty, and triggers a window alert.
Here is the code for my entire update profile modal:
const updateProfileModal = (currentUser) => {
// DOM Elements
const modal = document.querySelector(".modal");
const openModalButton = document.querySelector("#update-profile-btn");
const updateButton = document.querySelector("#update");
const updateProfileForm = document.querySelector(".profile-update-form");
const profileNameField = document.querySelector("#profile_name");
const closeModalButton = document.querySelector("#close-modal");
// Open "update profile" modal when clicked from dropdown menu
openModalButton.addEventListener("click", (e) => {
e.preventDefault();
// Hide the dropdown menu after opening update profile modal
document.querySelector(".dropdown-content").classList.toggle("show");
// Show user's email address and current username in placeholders
document.querySelector("#profile_email").placeholder = currentUser.email;
document.querySelector("#profile_name").placeholder = currentUser.displayName;
// If the modal doesn't have the CSS "show" class:
if (!modal.classList.contains("show")) {
// Toggle that class into the modal
modal.classList.toggle("show");
// Upon clicking on "update" button inside modal:
updateButton.addEventListener("click", (e) => {
e.preventDefault();
// Get value of new displayName
const newName = profileNameField.value;
// Update displayName.
if (newName !== "") {
updateUsername(newName)
updateProfileForm.reset();
modal.classList.toggle("show")
firebase.auth().currentUser.reload();
} else {
window.alert("Must choose a new name to update")
}
})
}
})
// Close profile updating modal upon clicking the "x"
closeModalButton.addEventListener("click", () => {
modal.classList.toggle("show");
})
}
Here is the updateUsername function which it uses:
// Update user's display name
const updateUsername = (newName) => {
auth.currentUser.updateProfile({
displayName: newName
}).then(() => {
// Once the name has been updated, append it to the user dropdown menu
updateDisplayNameInDOM(firebase.auth().currentUser)
});
}
Can you try to remove the updateProfileForm.reset(); from your code. It looks like this causes that the subsequent update fail.

Event listeners are not working but there is no error

I have an event listener listening to the submission of form which will be sent to firebase auth. A few hours ago, it was working fine. But suddenly, it just stopped. No error nothing. No event listeners were working. I restarted vs code and my computer. Where event listeners were defined -
import { smoothScroll } from './animations.js';
import { signup, logout } from './auth.js';
smoothScroll();
// Elements
const signupForm = document.querySelector('#signup-form');
const logoutBtn = document.querySelector('#logout-btn');
console.log(signupForm);
signupForm.addEventListener('submit', signup);
logoutBtn.addEventListener('click', logout);
Actual functions -
export function signup(e) {
e.preventDefault();
console.log('Sugb');
// User info
const email = signupForm['email'].value;
const password = signupForm['password'].value;
// Sign up
auth
.createUserWithEmailAndPassword(email, password)
.then((cred) => {
document.querySelector('.alert').classList.add('alert--show');
document.querySelector('.alert').textContent = 'User signed up';
loginState = true;
signupForm.reset();
})
.catch((error) => {
document
.querySelector('.alert')
.classList.remove('alert-success')
.add('alert-danger')
.add('alert--show');
document.querySelector('.alert').textContent = error.message;
});
}
export function logout(e) {
console.log('Logout');
alert('Logout');
}
Through a bit of debugging I found out that my functions were not getting called. This is the github repo https://github.com/akashshyamdev/doubt1 in case you need more info. Thanks in advance.
Since the signup form is present, when you add the event listener, but the event callback function is not called, I assume you changed the form after the event listener addition.
For this you must delegate the event to an element that is always there, typically the document. As the MDN doc says about the submit_event that it bubbles up, we can do this
Instead of
signupForm.addEventListener('submit', signup);
do this
document.addEventListener('submit', function(e) {
if (e.target.closest('#signup-form')) {
return signup(e);
}
return false;
});

Undo preventDefault() after API call

I am writing external script to check availability for e-commerce store. When "Add to basket" button is pressed, I'm calling my API and checking if product is available to order. However, I don't know how to undo preventDefault(). When condition is true, event under button should continue and product should be added to basket as without the script.
button.addEventListener('click', (event) => {
event.preventDefault();
fetch(`https://example.com/api.php?part=${partId}`)
.then(function (response) {
return response.json();
})
.then(function (jsonRes) {
console.log(JSON.stringify(jsonRes));
if (jsonRes.part.partFound == true) {
console.log('Found! Processing...');
// REMOVE preventDefault() and process
} else {
console.log('Not found! Aborting...', partId);
}
});
});
If your button is type="submit" change it totype="button"`. This
a) Won't submit the form
b) Means that you don't have to use preventDefault to prevent the form from submitting
That simply means you're left to decide how you want the data to be submitted, and you can either do that with another AJAX call to an API endpoint, or by submitting the whole form to the server - whichever is your setup.
// Grab the form and button, and add an event
// listener to the button
const form = document.querySelector('form');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
// Fake API call
function fakeAPI() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`API called!`)
}, 2000);
});
}
function handleClick() {
console.log('Clicked');
fakeAPI(2000).then(data => {
// If partfound submit the form data
// Either another fetch call to post the data,
// or `form.submit()` to post the whole form instead
});
}
<form>
<button type="button">
Click
</button>
</form>
you can try something like code below:
async function apiCall(onSuccess, onError) {
fetch(`https://example.com/api.php?part=${partId}`)
.then(function (response) {
return response.json();
})
.then(function (jsonRes) {
console.log(JSON.stringify(jsonRes));
if (jsonRes.part.partFound == true) {
console.log('Found! Processing...');
onSuccess(jsonRes);
} else {
console.log('Not found! Aborting...', partId);
onError();
}
});
}
button.addEventListener('click', (event) => {
// show loading or something
apiCall(function (response) {
// success
}, function () {
// error
});
});

submit search query if conditions are met

How would I go about integrating these two functions together so that when submitting the search form, it will first check the http get response, then depending on whether there was an error or not, either submit the form, or display an error message?
All that I've tried has either made the form not work at all, or not take into account the 'http.get function'.
var http = require("http");
var url = 'http://examplepage.com/';
search.submit(function (event) { // submit search query function
if (searchBox.val().length < 2) {
searchBox.focus();
event.preventDefault();
}
});
http.get(url, function (res) {
res.resume();
// successful - so submit search query
}).on('error', function () {
// unsuccessful - display error message
});
You should probably subscribe on click event for you button that triggers search, the go check the url and inside success handler do
Sample code of Click handler
http.get(url, function (res) {
// successful
if (searchBox.val().length < 2) {
$('your form selector').submit();
}
}).on('error', function () {
// unsuccessful - display error message
});

Categories