Home > Back-end >  error 'TS2532: Object is possibly 'undefined'
error 'TS2532: Object is possibly 'undefined'

Time:11-28

    useEffect(() => {
    firebase
      .firestore()
      .collection('likes')
      .doc(slug)
      .get()
      .then(res => {
        if (!res.data()) {
          console.log('No matching document');
        } else {
          setLikes(res.data().likes);
        }
      })
      .catch(err => console.log(err));
  }, []);

enter image description here

How can I solve the error. I'm trying to rebuild a web app example that uses Firebase Cloud Functions and Firestore.

CodePudding user response:

Using !res.data() will not tell Typescript that res.data() will not return undefined.

You would either have to store the result, and then type guard it:

.then(res => { // res is a DocumentSnapshot<DocumentData>
  const data = res.data(); // data is DocumentData | undefined
  if (!data) {
    console.log('No matching document');
  } else {
    setLikes(data.likes); // data is DocumentData
  }
})

or, you can use DataSnapshot#exists instead (preferred):

.then(res => { // res is a DocumentSnapshot<DocumentData>
  if (!res.exists) {
    console.log('No matching document');
  } else {
    setLikes(res.data().likes); // res is treated as a QueryDocumentSnapshot<DocumentData> (res.data() always returns DocumentData)
  }
})

Relevant API Reference:

CodePudding user response:

Because of res.data is a function which can return undefined, from a typescript's perspective, it's always possible that the result of a call would be undefined.

So, you can assign the result of res.data() to a variable and then use it instead of res.data()

  • Related