[Vuejs]-Async post with VueJS and Axios

0👍

If your post gets created successfully, that means if you make a get request to the posts endpoint, you would get that newly created post. As you would with a page refresh. So my point is to just directly insert the new post into the page, on the client side, after a successful post request. No get request necessary.

I don’t know the structure of your component hierarchy, or whether you’re using Vuex. But from the component that created the post, you would $emit an event that contains the new post data.

createPost: function() {

    let title = this.new_post_title;
    let content = this.new_post_content;
    let tags = this.new_post_tags;
    let status = this.status;

    let data = {
      'title': title, 
      'content': content, 
      'status': status,
    };

    axios.post("/wp-json/wp/v2/posts/", data, {headers: {'X-WP-Nonce': portal.nonce}})
    .then(response => {
      console.log(response);
      this.$emit('new-post',data)
    })
    .catch(e => {
      this.errors.push(e);
      console.log(this.errors);
    });

    this.new_post_title = '';
    this.new_post_content = '';
    this.new_post_tags = '';
  }

The parent of this component would catch the event, containing the data. Continue emitting events or passing props until you reach the component that displays the list. Once you’re in the list component, push the new post into the posts array, and it’ll show up on the page.

Leave a comment