1

I have problem with updating my array. When I click button second time and again I have only two or more records, same like last one I added. Someone knows the solution?

In the pictures can you se results of this function in console.

First time exit

second time exit

class Advertisement {
    advertisment:IAdvertisment = {
        id: 0,
        name: "",
        description: "",
        date: new Date()
    };

    private static ad:[IAdvertisment];
  
    add(id: Number, name: String, description: String, date: Date):void {
        this.advertisment.id = id;
        this.advertisment.name = name;
        this.advertisment.description = description;
        this.advertisment.date = date;

        if (Advertisement.ad) {
            Advertisement.ad.push(this.advertisment);
        }
        else {
            Advertisement.ad = [this.advertisment];
        }
    }

    get():[IAdvertisment]{
        return Advertisement.ad;
    }
}
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();
    }


    onButtonClick(){
        this.advertisment.add(this.getAmount(), this.state.name, this.state.description, this.state.date);
    }
 ...

   render() {
        return (<div>
        <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.menu_button} onClick={this.onButtonClick.bind(this)}>Add</button>
        </div>);
   }
}

1 Answer 1

1

I know. I must create object ones for every time.

class Advertisement {
 private static ad:[IAdvertisment];

 add(id: number, name: string, description: string, date: Date):void{

let advertisment:IAdvertisment = {
  id: id,
  name: name,
  description: description,
  date: new Date()
};

if(Advertisement.ad){
  
  Advertisement.ad.push(advertisment);

  console.log(Advertisement.ad);
  
}
else{
  Advertisement.ad = [advertisment];
}
};

Push Object in Array

Sign up to request clarification or add additional context in comments.

1 Comment

Could you put you email here, like "mariusz. at gmail etc"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.