Search code examples
javascriptreactjsfirebasegoogle-cloud-firestoremui-datatable

Can I have a conditional statement inside the componentDidMount?


Is there way that I can set a conditional statement inside the componentDidmount where if the payment method is by Card it will show the card's number? I'm using a muidatatable

  componentDidMount() {
    try {
      firestore
        .collection("orders")
        .onSnapshot((snapshot) => {
          const orders = [];
            const data = doc.data();
            orders.push({
              "Order ID": doc.id,
              "Payment method": data.paymentMethod.toUpperCase(),
                {data.paymentMethod == "card" ? (
            
                ): (

             )},
               });
          });
          this.setState({ orders: orders });
        });
    } catch (err) {
      console.log(err);
    }
  }


render() {
    return this.state.orders ? (
      <div>
        <MUIDataTable
          title={"Preparing"}
          columns={this.columns}
          data={this.state.orders}
          options={this.options}
        />
      </div>
    ) : (
      <p>Loading...</p>
    );
  }
}

Solution

  • If you want to have optional object properties you can pass conditional statements using the ternary operator (a ? b : c) inside an object, you need to use the spread operator to achieve so.

    orders.push({
      "Order ID": doc.id,
      "Payment method": data.paymentMethod.toUpperCase(),
      ...(data.paymentMethod == "card" ? { "Payment card": 1234 } : {}),
    });
    

    or the simpler way using &&:

    orders.push({
      "Order ID": doc.id,
      "Payment method": data.paymentMethod.toUpperCase(),
      ...(data.paymentMethod == "card" && { "Payment card": 1234 }),
    });