2021年4月5日星期一

React, update component after async function set

I want to add data and see in below, and also when I start app, I want see added records. But I can see it, when I'm try to writing something in the fields.

The thing is, the function that updates the static list is asynchronous. This function retrieves data from the database, but before assigning it to a variable, the page has been rendered. There is some way to wait for this variable or update information other way than when you try to type it in the fields. This is before the form is approved.

enter image description here

class AddAdvertisment extends React.Component <any, any> {   private advertisment;    constructor(props, state:IAdvertisment){   super(props);   this.onButtonClick = this.onButtonClick.bind(this);   this.state = state;   this.advertisment = new Advertisement(props);  }    onButtonClick(){this.setState(state => ({ showRecords: true }));}   ....    render() {     return (<React.Fragment>   <div className={styles.form}>   <section className={styles.section}>   <input id="name" onChange={this.updateName.bind(this)} ></input>   <input id="description" onChange={this.updateDescription.bind(this)} ></input>   <input type="date" id="date" onChange={this.updateDate.bind(this)} ></input>   <button className={styles.action_button} onClick={this.onButtonClick.bind(this)}>Add</button>   </section>   </div>   {<ShowAdvertismentList/>}   </React.Fragment>   );  }    class ShowAdvertismentList extends React.Component <any, any>{    render(){       let listItems;    let array = Advertisement.ad      if(array !== undefined){      listItems = array.map((item) =>      <React.Fragment>        <div className={styles.record}>          <p key={item.id+"a"} >Advertisment name is: {item.name}</p>           <p key={item.id+"b"} >Description: {item.description}</p>           <p key={item.id+"c"} >Date: {item.date}</p>         </div>      </React.Fragment>      );    }  return <div className={styles.adv_show}>{listItems}</div>;    class Advertisement extends React.Component {   public static ad:[IAdvertisment];   constructor(props){   super(props);    if(!Advertisement.ad){    this.select_from_db();    }   }   ....  select_from_db = async () => {   const res = await fetch('http://localhost:8000/select');   const odp = await res.json();     if(odp !== "brak danych")    odp.forEach(element => {      if(Advertisement.ad){        Advertisement.ad.push(element);      }      else{        Advertisement.ad = [element];  
https://stackoverflow.com/questions/66961615/react-update-component-after-async-function-set April 06, 2021 at 09:22AM

没有评论:

发表评论