MuaathAlhaddad
4/1/2020 - 11:26 AM

create - fetch API

FACTS

  • NO need to have paranthsis for function if you don't have parameters.
  • form alway requres a page refresh, while api is working behind the scene, use this event => @submit.prevent="createArticle"
  • button in the form are the responsible for routing the the form, instead the form header <form method="" action=""> , therefore, No need @click in button.

HTML

 <form @submit.prevent="createArticle()">
    <input name="title" v-model="article.title">
    <input name="body" v-model="article.body">
    <button>Add </button>
 </form>

JS

methods:{
  createArticle(){
    fetch('api/articles', {
      method: 'POST', 
      body: JSON.stringify(this.article),
      headers:{
        'content-type': 'application/json'
      }
    }).then(res => res.json())
      .then(data => {
        alert('article created');
        this.article.title = '';    //to clear the input
        this.article.body = '';
        this.fetchArticles        //to get the updated articles after creation
      }).catch(err => console.log(err));
  }
}