Home > Mobile >  Repopulating/Refresh table in React after pressing a button
Repopulating/Refresh table in React after pressing a button

Time:11-03

I have an input-text that allows the user to write the number of the order, and I have a button which validates if the order exists or if it was used already.

If the order is valid, it should retrieve the products (mongodb and meteor) of said order with its details. The first time that the user validates an order it works perfectly fine. However, if the user inputs another order, the table won't repopulate unless the user press the button again (after pressing it once). It is a dynamic table.

//Validating the order and Bringing the data of that Order
  validateOrder = () => {
const { products, productsPackaging, anotherCai } = this.state;
const cai = document.getElementById('cai').value;
if (cai && cai !== '') {
  this.setState({ validating: true });
  Meteor.call('getcai', cai, (err, res) => {
    this.setState({ validating: false });
    if (!err) {
      if (res.validated) {
        toastr.success('...');
      } else {
        toastr.info('...');
      }
      const tempProducts = [];
      const tempProductsPackaging = [];
      let tempCounter = 0;
      let tempAnotherCai = false;
      console.log(res);
      if (res.products && res.products.length > 0) {
        if (productsPackaging.length > 0) {
          tempAnotherCai = true;
        }
        for (let index = 0; index < res.products.length; index  ) {
          const element = { fakeId: `id-${index}`, articleId: res.products[index].Articulo_Id, originalAmountPills: res.products[index].amount };
          const element2 = { ...res.products[index], fakeId: `id-${index}` };

          tempProducts.push(element);
          tempProductsPackaging.push(element2);
        }
        tempCounter = res.products.length - 1;
      }
      this.setState({
        validated: res.validated,
        productsPackaging: tempProductsPackaging,
        products: tempProducts,
        counterId: tempCounter,
        anotherCai: tempAnotherCai,
      });
    } else {
      toastr.info(err.error);
    }
  });
} else {
  toastr.info('...');
    }
  }

Table and Button

      render() {
    const {
      products, validated, validating,
    } = this.state;
    return (
      <div className="modal fade" id="modalNewPackaging" tabIndex="-1" role="dialog" aria-labelledby="modalNewPackaging" aria-hidden="true">
        <div className="modal-dialog modal-dialog-centered" role="document" style={{ width: 1200, maxWidth: 'none' }}>

          <div className="modal-content" style={{ overflow: 'auto' }}>
            <div className="modal-header border-0">
              <h5 className="modal-title text-center">Agregar de Forma Manual</h5>
              <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div className="modal-body">
    //Order Input
                  <div className="row form-group">
                    <div className="col-6">
                      <input
                        required
                        id="cai"
                        type="text"
                        className="form-control text-primary"
                        style={{ borderColor: '#001689' }}
                        aria-describedby="inputGroup-sizing-sm"
                        aria-label="Small"
                        placeholder="CAI"
                        autoComplete="off"
                      />
    
                    </div>
                    <div className="col-6">
                      {
                        validating ? (
                          <LoaderComponent />
                        ) : (
    //Button that Validates the Order
                          <button onClick={this.validateOrder} type="button" className="btn btn-success">Validate</button>
    
                        )
                      }
                    </div>
    
                  </div>
                  <form>
                    <div className="row form-group">
    
                      <div className="col-12">
                        <input
                          id="nameClient"
                          type="text"
                          maxLength="50"
                          className="form-control text-primary"
                          style={{ borderColor: '#001689' }}
                          aria-describedby="inputGroup-sizing-sm"
                          aria-label="Small"
                          placeholder="Nombre de Paciente"
                          autoComplete="off"
                          disabled={!validated}
                        />
                      </div>
                    </div>
                    {
                      validating ? (
                        <LoaderComponent />
                      ) : validated ? (
                        <div className="container">
                          <div className="container" style={{ maxHeight: '250px', overflowX: 'auto', overflowY: 'auto' }}>
    
                            <div className="card">
                              <div className="card-body">
    
                                <table className="table" style={{ width: '100%' }}>
                                  <thead>
                                    <tr>
                                      <th>Product's Name</th>
                                         ...
                                    </tr>
                                  </thead>
                                  <tbody>
                                    {
                                      products.map((product, index) => (
                                        <tr key={product.fakeId}>
                                          <td>
                                            <input
                                              required
                                              defaultValue={this.defaultValue(product.fakeId, 'productName')}
                                              id={`productName${product.fakeId}`}
                                              name="productName"
                                              type="text"
                                              className="form-control"
                                              style={{ borderColor: '#001689' }}
                                              autoComplete="off"
                                              list="suggestions"
                                              
                                            />
              

                            </td>
                                              //...
  ))
                                }
                              </tbody>
                            </table>
                </div>
              </div>
            </div>
          </div>
                  );
  }
}  
                    

Default Value

defaultValue = (fakeId, inputName) => {
    const { productsPackaging, anotherCai } = this.state;
    const index = productsPackaging.findIndex(function findIt(item) {
      return item.fakeId === fakeId;
    });

    if (index === -1) {
      return '';
    }
    // console.log(fakeId);
    // console.log(index);
    // console.log('Iam in');
    if (inputName.includes('productName')) {
      console.log(productsPackaging[index].Articulo_Nombre);
      //if (!anotherCai) {
      return productsPackaging[index].Articulo_Nombre;
      // } else {
      //   document.getElementById(`productName${fakeId}`).value = productsPackaging[index].Articulo_Nombre;
      // }
    }

  }

CodePudding user response:

If you want to change the order based on what is being types into the input. You will have to handle that in a onChange event in the input. Otherwise it will require a a button click by default.

CodePudding user response:

Add a useEffect hook and pass the state as a dependency that changes into the useEffect hook and it will work as it is supposed to .

 useEffect(()=>{},[theChangingState])
  • Related