Search code examples
apivue.jsstoreaxiosvuex

not able to add user input into a rest api using store


This is my mainpage where I have a form which I want to integrate with an API so that I can save my data there:

<div>
    <span>userId</span> <input type="text" v-model="info.userId">
</div>
<br>
<div>
    <span>id</span> <input type="text" v-model="info.id">
</div>
<br>
<div>
    <span>title</span> <input type="text" v-model="info.title">
</div>
<br>
<div>
    <span>body</span> <input type="text" v-model="info.body" >
</div>
<br>

<input type="submit" @click="addtoAPI">

This is mainpage.js code where i have declared the the object named "info" which will hold all the fileds of my form and there is also the "addtoAPI" method which basically access the store's action

    data(){
        return{
         info:{
           userId:'',
           id:'',
           title:'',
           body:''
         }
        }
      },
     methods:{
     addtoAPI(){
       this.$store.dispatch('addtoapi',this.info)
     }

This is my store.js code where I have added an action named addtoapi which basically stores data in respective fields

 actions: {
         addtoapi :({commit},info) =>{
                let newuser={
                  userId:this.info.userId,
                  id:this.info.id,
                  title:this.info.title,
                  body:this.info.body
                }
                console.log(newuser);
               axios.post('https://jsonplaceholder.typicode.com/posts/',newuser)
                  .then((response) =>{
                    console.log(response);
                  })
                  .catch((error) => {
                    console.log(error);
                  })
              }
    }

Now when I am running this I am getting this error please help me with this because I have already added userId.

store.js?adc6:50 Uncaught TypeError: Cannot read property 'userId' of undefined
        at Store.addtoapi (store.js?adc6:50)
        at Array.wrappedActionHandler (vuex.esm.js?358c:704)
        at Store.dispatch (vuex.esm.js?358c:426)
        at Store.boundDispatch [as dispatch] (vuex.esm.js?358c:332)
        at VueComponent.addtoAPI (Mainpage.js?4af6:45)
        at invoker (vue.esm.js?efeb:2027)
        at HTMLInputElement.fn._withTask.fn._withTask (vue.esm.js?efeb:1826)

Solution

  • In your store's actions you've made a mistake, you're trying to access to property info of this (that's why it throw an error with undefined) :

    let newuser= {
          userId:this.info.userId,
          id:this.info.id,
          title:this.info.title,
          body:this.info.body
     }
    

    Need to be replaced by this:

    let newuser = {
        userId: info.userId,
        id: info.id,
        title: info.title,
        body: info.body
    }