Ensuring a unique email address in the database with the updateProfile() function

Implementing a method to check if an email already exists in Firestore when using the updateProfile() function is currently a challenge for me. I tried creating a test method in MyAccount.vue, but it does not work as expected. Ideally, I would like the method to verify the existence of the email before updating anything.

./src/views/MyAccount.vue

import { mapState } from 'vuex';

export default {
    data() {
        return {
            user: {
                username: '',
                email: '',
                password: ''
            }
        };
    },

    computed: {
        ...mapState(['userProfile']),
    },

    methods: {
        updateProfile() {
            this.$store.dispatch('updateProfile', {
                username:
                    this.user.username !== ''
                        ? this.user.username
                        : this.userProfile.username,
                email:
                    this.user.email !== ''
                        ? this.user.email
                        : this.userProfile.email,
                password:
                    this.user.password !== ''
                        ? this.user.password
                        : this.userProfile.password
            });

            this.user.username = '';
            this.user.email = '';
            this.user.password = '';

            this.showSuccess = true;

            setTimeout(() => {
                this.showSuccess = false;
            }, 2000);
        }
    }
};

./src/store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import * as fb from '../firebase';
import router from '../router/index';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        userProfile: {},
        notes: []
    },

    mutations: {
        setUserProfile(state, val) {
            state.userProfile = val;
        },

        setNotes(state, val) {
            state.notes = val;
        }
    },

    actions: {
        async updateProfile({ commit, dispatch }, user) {
            const userId = fb.auth.currentUser.uid;

            await fb.usersCollection.doc(userId).update({
                username: user.username,
                email: user.email,
                password: user.password
            });

            dispatch('fetchUserProfile', { uid: userId });
        },

        async fetchUserProfile({ commit }, user) {
            // fetching user profile
            const userProfile = await fb.usersCollection.doc(user.uid).get();

            // setting user profile in state
            commit('setUserProfile', userProfile.data());

            // redirect to dashboard page
            if (router.currentRoute.path === '/login') {
                router.push('/');
            }
        }
    },
    modules: {}
});

export default store;

Answer №1

To avoid issues when updating, consider the following:

const existing = await fb.usersCollection.where('email', '==', user.email).get()
if (existing.empty === true) {
  // Proceed with the update as the email is not already in use
}

It's recommended to always convert emails to lowercase before querying or saving them in the database for consistency

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it necessary to utilize the super keyword when extending a React.Component?

What is the purpose of using 'super' in the code snippet below? What specific functionality from React.Component does it need to access with 'super'? If CommentList is already extending React.Component, why is 'super' necessar ...

How can you include a backslash in data when using AJAX?

Is it possible to send PHP code via AJAX in order to save it in a file? I'm encountering an issue where backslashes are disappearing when trying to send the following code: ...$buffer = "if(\$_POST){".chr(13).chr(10);... Below is the code snipp ...

I encountered an issue while attempting to download a zipped folder using an AXIOS get request, as the folder appeared

I have developed an application in NodeJs for the backend and VueJS for the frontend. I am attempting to download a zip file that is generated within the app on the frontend using the code snippet below: const downloadZIP = () => { AXIOS_REQUEST( ...

"Implementing a monorepo with turborepo for seamless deployment on Vercel: A step-by-step

There has been recent news about Turborepo being acquired by Vercel, sparking my interest to dive into it. To start, I initiated a turbo repo project with the following command: pnpx create-turbo Afterwards, I attempted to deploy it on Vercel by referring ...

Sorry, we couldn't locate the API route you are looking for

Within my Next.js project resides the file main/app/api/worker-callback/route.ts: import { NextApiResponse } from "next"; import { NextResponse } from "next/server"; type ResponseData = { error?: string }; export async function PO ...

Trouble with IFormCollection not retrieving individual form data

I've been working on an asp.net core MVC project where I encountered a requirement to add dynamic fields to a view that already has a form with static fields. These dynamic fields are fetched from the database and need to be submitted along with the s ...

Angular - Issue with Select Element - NgFor directive is limited to binding with Iterable objects like Arrays

I have a REST API build in NodeJS that sends me JSON data as a response. I utilize this data to populate the options of a select input element: [{"id":1,"tasktype":"Programming","taskvalue":350,"date":"2018-08-02T03:00:00.000Z","status":1},{"id":2,"taskty ...

Steps for revealing a section of a webpage by completing an HTML form

Looking for a way to validate and store data from an HTML form in order to reveal a specific section of my webpage. Here's the scenario: I run an online shop and want to capture leads. On my landing page, I want to only show the purchase button and p ...

Show a directional indicator on hover in the date selection tool

I am currently using a datepicker that looks like this: https://i.sstatic.net/XsrTO.png When I hover over it, three arrows appear to change days or show the calendar. However, I would like to remove these arrows. Here is the code snippet: link: functi ...

Issue in Angular Material: The export 'MaterialComponents' could not be located in './material/material.module'

I'm relatively new to Angular and I am encountering some difficulties when trying to export a material module. The error message that appears is as follows: (Failed to compile.) ./src/app/app.module.ts 17:12-30 "export 'MaterialComponents&ap ...

Add to the current values of the REACT Form template property

I am new to working with REACT and I have been exploring whether it is possible to append a REACT Form control property value in order to enhance its functionality. To streamline the validation process, I have created a validation template that leverages ...

Dynamically change the content of the DataTable by utilizing jQuery

I am facing an issue with updating a DataTable using jQuery when the contents of the table are modified. Initially, I have a HTML table with an empty tbody, which is populated dynamically based on selected filters such as select options. The table uses Dat ...

Why is it that I am unable to properly encode this URL in node.js?

$node querystring = require('querystring') var dict = { 'q': 'what\'s up' }; var url = 'http://google.com/?q=' + querystring.stringify(dict); url = encodeURIComponent(url); console.log(url); Here is the re ...

Alternatives for storing IDs for future reference in HTML beyond data attributes

As I delved into an intriguing article, it mentioned the following, According to the article, external software should not tamper with custom data attributes. It would be inappropriate to markup contact or event details using such attributes... Despite ...

"Discover the steps to seamlessly display office documents on a webpage, similar to the functionality of

I am working on a project that involves using Node.js for the backend and AngularJS for the frontend. I need to be able to open Office files (.doc, .ppt, etc.) directly on my webpage. These files are stored on an Amazon S3 server. I am looking to implemen ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...

In the world of programming, there exists a mysterious creature known as

I've been experimenting with different methods, but nothing seems to be working for me. What I am attempting to accomplish is <?php $php_var = a-thing; echo ' <script text/JavaScript> document.cookie = "arrayid"+&apos ...

Typescript struggles to comprehend the nullish-coalescing operator

Within my Vue + TypeScript application, I've incorporated an external package called @moj/pagination-layout. This package utilizes the nullish operator internally. However, when attempting to run the build process, it encounters a failure and presents ...

The fulfillment of the post route for the login page is awaiting a request in the browser using Express Node.js

The router is currently waiting for a response (request pending) router.post('/loginpost',(req,res,next)=>{ var email=req.body.email; var password=req.body.password; var selectsql=`SELECT * FROM client WHERE em ...

What happens when Image Buttons are clicked in SAPUI5 and their onchange event is triggered

Is there a way to update the image on a button after it has been clicked? I want it to switch to a different image when activated. var offButton = new sap.ui.commons.Button({ id : "offIcon", icon : "img/off.png" , press :functio ...