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

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.

Related

Navigating back when user confirms in browser modal

I am trying to alert the user of unsaved changes when they use the back button in the browser and it works when the user hits cancel on the confirm modal but when they click ok to confirm they want to go back the page does not go back.
These are my funcitons for handling back:
const handleBrowserBackBtn = () => {
handleBackClick();
window.history.pushState(null, document.title, window.location.href);
}
useLayoutEffect(() => {
window.history.pushState(null, document.title, window.location.href);
window.addEventListener("popstate", handleBrowserBackBtn);
return () => {
window.removeEventListener("popstate", handleBrowserBackBtn);
};
});
const handleBackClick = () => {
if(addingNew || editing){
if(confirm("You have unsaved changes. Are you sure you want to go back?")){
window.location.back()
};
}
}
I am trying to send the user back to the home screen. But I get this endless loop of confirm pop up.
try to use this for your app :

When the user changes the button onClick again executes

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");
}
};

Fire dialog box when user clicks on external links

There goal is to prevent users from redirect on accidental clicks on external links, when user fills up the form.
Problem: the whole code has to be abstract. I don't know which links user clicks, I don't know whether the form is fully or partly filled.
If the form is empty, then redirect user without dialog/confirmation box.
Here's code:
function exit_confirm(event) {
let url;
if (event.target.nodeName === "a") {
url = event.target.getAttribute('href');
}
if (window.confirm('Do you want to leave the site?')) {
window.location.href = url;
}
}
function getAllElementsWithDataAttribute() {
return document.querySelectorAll('*[data-]');
}
function registerOnClickChangeKeydownEventsOfElementsWith() {
let elementsWithDataAttribute = getAllElementsWithDataAttribute();
['click', 'change', 'keydown'].forEach(evt => {
elementsWithDataAttribute.addEventListener(evt, exit_confirm, false);
});
}
The code is not a final version.
I have to get url from a clicked link and pass it to window.location.href
I also need to check a clicked link if it is an external link.
*[data-] - here has to be smthing that defines the link

function onClick() - cart not adding - what's wrong?

I have a product page on Shopify with an Add to Cart button.
On click, the product gets added to cart and page redirects to another upsell product.
After they add upsell product to cart, it goes to checkout page BUT it's only displaying the upsell product and not the first product user wanted to buy. What's wrong with the code below?
How do I make both products appear in checkout?
<script>
function redirectToUpsellPageHandler(wrapper) {
var upsellPageUrl = '/clientproducts/cryogenic-storage';
var addToCartButton = wrapper.querySelector('.sqs-add-to-cart-button');
var productVariants = wrapper.querySelector('.product-variants');
if (addToCartButton) {
addToCartButton.addEventListener('click', onClick);
}
function isVariantInStock() {
return productVariants.getAttribute('data-variant-in-stock');
}
function onClick() {
if (productVariants && isVariantInStock() || !productVariants) {
setTimeout(function() {
document.location.href = upsellPageUrl;
}, 1000);
}
}
}
function redirectToUpsellPage() {
// Product Page
var productPage = document.querySelector('.collection-type-products.view-item');
if (productPage) {
redirectToUpsellPageHandler(productPage);
}
// Product Blocks
var productBlocks = [].slice.call(document.querySelectorAll('.sqs-block-product'));
productBlocks.forEach(redirectToUpsellPageHandler);
}
document.addEventListener('DOMContentLoaded', redirectToUpsellPage);
window.addEventListener('mercury:load', redirectToUpsellPage);
</script>
Add some console.logs and make sure you're getting into your onClick function. If you're not there may be some type of issue with using a function named onClick since that is a reserved function in jQuery or JS.

Node.JS & Socket.io - Checking if the tab is selected

For my chat, I want to have notifications. These notifications will act like Gitter's notifications, where it changes the html title to show you have a message. I've googled how to accomplish this, but all answers only worked by checking when the tab is changed. For example,
socket.on('chat message', function (msg) {
// Append the message
appendMessage(msg);
// Check if the window is focused
if (window.onfocus) {
// If it is, there's no need to show there's a new message
document.title = "ChatProject";
}else{
// If the user is on another tab, show there's a new message
document.title = "[!] ChatProject";
}
});
With the code above, it always shows the notification whether you're on the tab or not. How do I get it to show only when there's a new message?
window.onfocus is an event. Not a state.
By adding a getter and setter to the events you can get the behavior described.
///////////////////////
//Setting OnFocusSate//
///////////////////////
var isFocused = true;
function onFocus(){
isFocused = true;
};
function onBlur() {
isFocused = false;
};
window.onfocus = onFocus;
window.onblur = onBlur;
///////////////////////
//Example Event Check//
///////////////////////
socket.on('chat message', function (msg) {
// Append the message
appendMessage(msg);
// Check if the window is focused
if (isFocused) {
// If it is, there's no need to show there's a new message
document.title = "ChatProject";
}else{
// If the user is on another tab, show there's a new message
document.title = "[!] ChatProject";
}
});
Cryptic: This works, but when you click back on the tab, the notification doesn't go away. So, we'd have to change the if statement to this
if (!isFocused) {
// If the user is on another tab, show there's a new message
document.title = "[!] ChatProject";
}
Then add this under it
window.onfocus = function() {
document.title = "ChatProject";
}

Categories