JS3
JS3

Reputation: 1849

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));
  }

Upvotes: 1

Views: 117

Answers (3)

Sanoodia
Sanoodia

Reputation: 925

use OR || operator if city is undefined

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

Upvotes: 1

Shahzaib Shahid
Shahzaib Shahid

Reputation: 1431

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}`,

Upvotes: 1

Fraddy
Fraddy

Reputation: 331

You can use nullish coalescing operator.

data.city ?? ""

Upvotes: 0

Related Questions