How to create an update api to update data in firestore using react

Viewed 25

I am fairly new to firebase and trying to make a web app using firebase and react however I am not able to update user details on firebase.

whenever I press the update button I want to have the fields already filled from the firestore but I am unable to do so. here is the image of the update page

following is the updateUser api I wrote in typescript

export const updateUser = functions.https.onRequest((req, res) => {
  // @ts-ignore
  // ts-lint:disable-next-line
  corsHandler(req, res, async () => {
    const {uid,email, university, sem} = req.body;
    const user = await admin.auth().updateUser(uid, {email});
    await admin.firestore().collection('users').doc(uid).update(
      {
        email: email,
        university: university,
        sem: sem
      }
    );
    res.send(user);
  });
})

update.js

import React, { useState } from 'react'
import { useAuthState, db, firebaseApp } from './firebase'
import axios from 'axios'
import 'firebase/firestore'


export const Update = () => {

    const { user } = useAuthState()
    console.log(user);   
    console.log(user?.uid);

    const handleUpdate = (e) => {
        e.preventDefault();
        axios.put(`http://localhost:5001/klevr-cdcf3/us-central1/updateUser`, {...details, uid: user?.uid})
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
    };


    const initialState = {
        email: user?.email,
        university: '',
        sem:'' ,
    }

    const [details, setDetails] = useState(initialState);
    console.log(details);
    return (
        <div>
            <h1>Update</h1>

            <form>
            Email <input type = 'email' value={details.email} placeholder='enter email address' onChange={(e) => setDetails({...details, email: e.target.value})} /><br /><br />
            University <input type = 'text' value={details.university} placeholder='enter your university' onChange={(e) => setDetails({...details, university: e.target.value})} /><br /><br />
            Semester <input type = 'text' value={details.sem} placeholder='enter the semester' onChange={(e) => setDetails({...details, sem: e.target.value})} /><br /><br />

            <button type = 'submit' onClick={handleUpdate}>Update</button>
        </form>
        </div>
    )
}

0 Answers
Related