I have a POST method that the user will post an data to the server. The POST method is successfully working but I don't want to refresh my page after posting instead I want to update the array that I am looping through.
I want to update that array using the push
method of an array base from the response of the post. My end goal here is to update the posts without refreshing the page like a real time update.
So here is what I have done so far.
posts: any = [];
fake_post: any = [];
success: boolean = false;
In my constructor
events.subscribe('post:created-successfully', (data) => {
const promise = Promise.resolve(data)
promise.then(() => this.success = true).then(() => this.fake_post = [])
.then(() => setTimeout(() => { this.success = false }, 1000))
.then(data => this.posts.push(data))
.then(() => console.log(this.posts))
});
and in my submit()
method:
submit() {
this.showLoader();
if (this.form.value.title && this.form.value.author) {
this.loading.dismiss();
this.data = this.form.value;
console.log(this.data);
this.view.dismiss( this.data );
this.postApiProvider.createPost(this.data).then((response : addReponse) => {
console.log('Provider response', response);
this.data = response;
})
.then(() => this.events.publish('post:created-successfully', this.data))
.then(() => this.presentToast(this.data))
.catch(err => console.log(err));
} else {
console.log('Something went wrong.')
}
}
when I want console.log
the array after the push
method of an array this is what I got:
0
:
{title: "Async and Await", author: "Jayz", id: 1}
1
:
{title: "Promises", author: "Jayz", id: 2}
2
:
{title: "Callbacks", author: "Jayz", id: 3}
3
:
{title: "1234", author: "1234", id: 4}
4
:
135
That indexOf
4 id in the array is the post that I had created but I didn't return an object.
So how would I deal with this?
And as a bonus how can I refactor my promises using async and await?
Appreciate if someone could help. Thanks in advance.