简体   繁体   中英

Showing undefined value

I have this table where I fetch the data using firestore. There were some cases where this data is empty. I have this address where city is empty it would show undefined . How would I just display it as blank instead of the word "undefined"?

componentDidMount() {
    firestore
      .collection("users")
      .get()
      .then((snapshot) => {
        const users = [];
        snapshot.forEach((doc) => {
          const data = doc.data();
          users.push({
            "User ID": doc.id,
            Address: data.address + ", " + data.city + ", " + data.provice,
                }),
          });
        });
        this.setState({ users: users });
      })
      .catch((error) => console.log(error));
  }

You can use nullish coalescing operator.

data.city?? ""

use OR || operator if city is undefined

Address: data.address + ", " + data.city || "" + ", " + data.provice

Instead of using + you can do the following, It will simplify the code readability and cater to your use case.

 Address: `${data.address} , ${data.city || ""} , ${data.provice}`,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM