Home > Enterprise >  What does setDoc function return?
What does setDoc function return?

Time:12-18

I'm using firebase in my reactjs typescript project. I want to write a document in firebase and I'm using setDoc to do this job.

import { doc, setDoc } from 'firebase/firestore';

setDoc(doc(database, `path`), objData)

When you check the function return it says Promise<...>. But, how am I supposed to use then() catch() promise handlers if I don't know what the promise returns when it fullfil/reject?

CodePudding user response:

I'm not very familiar with Firebase but after looking around it seems the return is just going to be whether or not the setDoc() was successful. So the .then() would mean yes and the .catch() would mean no. So really all you would want is something like this

import { doc, setDoc } from 'firebase/firestore';

setDoc(doc(database, `path`), objData)
.then(() => {
console.log("Successful")})
.catch((error) => {
console.log(`Unsuccessful returned error ${error}`)});

Again I am not fully sure about the exact values returned as I could not find much but if there is a result value given you would place it in the .then((result) => {console.log(result)}).

CodePudding user response:

The firebase documentation suggest using await, so here you have a complete example of error handling with await and cleanup with finally.

import { doc, setDoc } from 'firebase/firestore';


async function run() {
    try {
        await setDoc(doc(database, `path`), objData)
    } catch (e) {
        console.error(e); // handle your error here
    } finally {
        console.log('Cleanup here'); // cleanup, always executed
    }
}

run();

CodePudding user response:

In Typescript, you don't need to specify the promise return type precisely. Here's an example of how to use promise handlers with setDoc:

import { doc, setDoc } from 'firebase/firestore';

setDoc(doc(database, `path`), objData)
  .then((data) => {console.log('data', data);})
  .catch((err) => {console.log('err', err);})
  • Related