fetch data with vue and sockets












0















I am using vuejs (CLI 3) with axios and sockets. My backend is NodeJs.



Html (view all users):



...
<ul v-if="users.length > 0">
<li v-for="user in users" :key="user.id">
<router-link :to="'/oneuser/' + user.permalink" tag="li" active-class="active" @click.native="setmyid(user._id)">
<a>{{ user.name }} - {{ user.last_name }}</a>
</router-link>
</li>
</ul>
...
<script>
import axios from 'axios'
import io from 'socket.io-client'
export default {
name: 'get-user',
data () {
return {
users: ,
socket: io('localhost:7000')
}
},
methods: {
mycall () {
axios.get('http://localhost:7000/api/users')
.then(res => {
// console.log(res)
const data = res.data
const users =
for (let key in data) {
const user = data[key]
user.id = key
users.push(user)
}
// console.log(users)
this.users = users
})
.catch(error => console.log(error))
}
}
mounted () {
this.mycall()
this.socket.on('user-deleted', function (data) {
this.mycall()
})
}
}
</script>


Html (user view):



<script>
import axios from 'axios'
export default {
name: 'one-user',
data () {
return {
name: '',
surname: '',
id: localStorage.getItem('usId'),
socket: io('localhost:7000')
}
},
mounted () {
axios.get('http://localhost:7000/api/get-user/' + this.id)
.then(res => {
const data = res.data
this.name = data.name
this.surname = data.last_name
})
.catch(error => console.log(error))
},
methods: {
mySubmit () {
const formData = {
_id: this.id
}
axios.post('http://localhost:7000/api/delete-user', formData)
.then(this.$router.push({ name: 'get-user' }))
.catch(error => console.log(error))
}
}
}
</script>


backend NodeJs:



controller.postDeleteUser = function(req,res){        
User.deleteOne({"_id" : req.body._id}, function(err){
io.emit('user-deleted', req.body._id);
res.send('ok');
});
};


When I go to user view and delete the user then it directs me to view all users. I have two major problems here.



1) After redirect, I saw again all the users even the deleted one. In my database the user has deleted correctly.



2) I don't know where exactly and how to use sockets in my code.



I am using in the front the socket.io-client npm plugin. Also I don't want to use (and I don't use it in my code) vue-socket.io because IE 11 and below version are not supported and it throws me some errors.



What I have tried so far:



1) Using watch like this:



watch: {
users: function (newValue) {
newValue = this.mycall()
}
}


This is very bad for browser performance, because always call request from the browser.



2) use beforeUpdate or Updated life-cycle:



updated () {
this.mycall()
}


That works but has bad performance. It makes requests many times to the server.



3) or that with sockets



updated () {     
this.socket.on('user-deleted', function (data) {
this.mycall()
})
}


and that throws me an error:



this.mycall() is not a function


What am I doing wrong?
Where to put the code with sockets?










share|improve this question



























    0















    I am using vuejs (CLI 3) with axios and sockets. My backend is NodeJs.



    Html (view all users):



    ...
    <ul v-if="users.length > 0">
    <li v-for="user in users" :key="user.id">
    <router-link :to="'/oneuser/' + user.permalink" tag="li" active-class="active" @click.native="setmyid(user._id)">
    <a>{{ user.name }} - {{ user.last_name }}</a>
    </router-link>
    </li>
    </ul>
    ...
    <script>
    import axios from 'axios'
    import io from 'socket.io-client'
    export default {
    name: 'get-user',
    data () {
    return {
    users: ,
    socket: io('localhost:7000')
    }
    },
    methods: {
    mycall () {
    axios.get('http://localhost:7000/api/users')
    .then(res => {
    // console.log(res)
    const data = res.data
    const users =
    for (let key in data) {
    const user = data[key]
    user.id = key
    users.push(user)
    }
    // console.log(users)
    this.users = users
    })
    .catch(error => console.log(error))
    }
    }
    mounted () {
    this.mycall()
    this.socket.on('user-deleted', function (data) {
    this.mycall()
    })
    }
    }
    </script>


    Html (user view):



    <script>
    import axios from 'axios'
    export default {
    name: 'one-user',
    data () {
    return {
    name: '',
    surname: '',
    id: localStorage.getItem('usId'),
    socket: io('localhost:7000')
    }
    },
    mounted () {
    axios.get('http://localhost:7000/api/get-user/' + this.id)
    .then(res => {
    const data = res.data
    this.name = data.name
    this.surname = data.last_name
    })
    .catch(error => console.log(error))
    },
    methods: {
    mySubmit () {
    const formData = {
    _id: this.id
    }
    axios.post('http://localhost:7000/api/delete-user', formData)
    .then(this.$router.push({ name: 'get-user' }))
    .catch(error => console.log(error))
    }
    }
    }
    </script>


    backend NodeJs:



    controller.postDeleteUser = function(req,res){        
    User.deleteOne({"_id" : req.body._id}, function(err){
    io.emit('user-deleted', req.body._id);
    res.send('ok');
    });
    };


    When I go to user view and delete the user then it directs me to view all users. I have two major problems here.



    1) After redirect, I saw again all the users even the deleted one. In my database the user has deleted correctly.



    2) I don't know where exactly and how to use sockets in my code.



    I am using in the front the socket.io-client npm plugin. Also I don't want to use (and I don't use it in my code) vue-socket.io because IE 11 and below version are not supported and it throws me some errors.



    What I have tried so far:



    1) Using watch like this:



    watch: {
    users: function (newValue) {
    newValue = this.mycall()
    }
    }


    This is very bad for browser performance, because always call request from the browser.



    2) use beforeUpdate or Updated life-cycle:



    updated () {
    this.mycall()
    }


    That works but has bad performance. It makes requests many times to the server.



    3) or that with sockets



    updated () {     
    this.socket.on('user-deleted', function (data) {
    this.mycall()
    })
    }


    and that throws me an error:



    this.mycall() is not a function


    What am I doing wrong?
    Where to put the code with sockets?










    share|improve this question

























      0












      0








      0








      I am using vuejs (CLI 3) with axios and sockets. My backend is NodeJs.



      Html (view all users):



      ...
      <ul v-if="users.length > 0">
      <li v-for="user in users" :key="user.id">
      <router-link :to="'/oneuser/' + user.permalink" tag="li" active-class="active" @click.native="setmyid(user._id)">
      <a>{{ user.name }} - {{ user.last_name }}</a>
      </router-link>
      </li>
      </ul>
      ...
      <script>
      import axios from 'axios'
      import io from 'socket.io-client'
      export default {
      name: 'get-user',
      data () {
      return {
      users: ,
      socket: io('localhost:7000')
      }
      },
      methods: {
      mycall () {
      axios.get('http://localhost:7000/api/users')
      .then(res => {
      // console.log(res)
      const data = res.data
      const users =
      for (let key in data) {
      const user = data[key]
      user.id = key
      users.push(user)
      }
      // console.log(users)
      this.users = users
      })
      .catch(error => console.log(error))
      }
      }
      mounted () {
      this.mycall()
      this.socket.on('user-deleted', function (data) {
      this.mycall()
      })
      }
      }
      </script>


      Html (user view):



      <script>
      import axios from 'axios'
      export default {
      name: 'one-user',
      data () {
      return {
      name: '',
      surname: '',
      id: localStorage.getItem('usId'),
      socket: io('localhost:7000')
      }
      },
      mounted () {
      axios.get('http://localhost:7000/api/get-user/' + this.id)
      .then(res => {
      const data = res.data
      this.name = data.name
      this.surname = data.last_name
      })
      .catch(error => console.log(error))
      },
      methods: {
      mySubmit () {
      const formData = {
      _id: this.id
      }
      axios.post('http://localhost:7000/api/delete-user', formData)
      .then(this.$router.push({ name: 'get-user' }))
      .catch(error => console.log(error))
      }
      }
      }
      </script>


      backend NodeJs:



      controller.postDeleteUser = function(req,res){        
      User.deleteOne({"_id" : req.body._id}, function(err){
      io.emit('user-deleted', req.body._id);
      res.send('ok');
      });
      };


      When I go to user view and delete the user then it directs me to view all users. I have two major problems here.



      1) After redirect, I saw again all the users even the deleted one. In my database the user has deleted correctly.



      2) I don't know where exactly and how to use sockets in my code.



      I am using in the front the socket.io-client npm plugin. Also I don't want to use (and I don't use it in my code) vue-socket.io because IE 11 and below version are not supported and it throws me some errors.



      What I have tried so far:



      1) Using watch like this:



      watch: {
      users: function (newValue) {
      newValue = this.mycall()
      }
      }


      This is very bad for browser performance, because always call request from the browser.



      2) use beforeUpdate or Updated life-cycle:



      updated () {
      this.mycall()
      }


      That works but has bad performance. It makes requests many times to the server.



      3) or that with sockets



      updated () {     
      this.socket.on('user-deleted', function (data) {
      this.mycall()
      })
      }


      and that throws me an error:



      this.mycall() is not a function


      What am I doing wrong?
      Where to put the code with sockets?










      share|improve this question














      I am using vuejs (CLI 3) with axios and sockets. My backend is NodeJs.



      Html (view all users):



      ...
      <ul v-if="users.length > 0">
      <li v-for="user in users" :key="user.id">
      <router-link :to="'/oneuser/' + user.permalink" tag="li" active-class="active" @click.native="setmyid(user._id)">
      <a>{{ user.name }} - {{ user.last_name }}</a>
      </router-link>
      </li>
      </ul>
      ...
      <script>
      import axios from 'axios'
      import io from 'socket.io-client'
      export default {
      name: 'get-user',
      data () {
      return {
      users: ,
      socket: io('localhost:7000')
      }
      },
      methods: {
      mycall () {
      axios.get('http://localhost:7000/api/users')
      .then(res => {
      // console.log(res)
      const data = res.data
      const users =
      for (let key in data) {
      const user = data[key]
      user.id = key
      users.push(user)
      }
      // console.log(users)
      this.users = users
      })
      .catch(error => console.log(error))
      }
      }
      mounted () {
      this.mycall()
      this.socket.on('user-deleted', function (data) {
      this.mycall()
      })
      }
      }
      </script>


      Html (user view):



      <script>
      import axios from 'axios'
      export default {
      name: 'one-user',
      data () {
      return {
      name: '',
      surname: '',
      id: localStorage.getItem('usId'),
      socket: io('localhost:7000')
      }
      },
      mounted () {
      axios.get('http://localhost:7000/api/get-user/' + this.id)
      .then(res => {
      const data = res.data
      this.name = data.name
      this.surname = data.last_name
      })
      .catch(error => console.log(error))
      },
      methods: {
      mySubmit () {
      const formData = {
      _id: this.id
      }
      axios.post('http://localhost:7000/api/delete-user', formData)
      .then(this.$router.push({ name: 'get-user' }))
      .catch(error => console.log(error))
      }
      }
      }
      </script>


      backend NodeJs:



      controller.postDeleteUser = function(req,res){        
      User.deleteOne({"_id" : req.body._id}, function(err){
      io.emit('user-deleted', req.body._id);
      res.send('ok');
      });
      };


      When I go to user view and delete the user then it directs me to view all users. I have two major problems here.



      1) After redirect, I saw again all the users even the deleted one. In my database the user has deleted correctly.



      2) I don't know where exactly and how to use sockets in my code.



      I am using in the front the socket.io-client npm plugin. Also I don't want to use (and I don't use it in my code) vue-socket.io because IE 11 and below version are not supported and it throws me some errors.



      What I have tried so far:



      1) Using watch like this:



      watch: {
      users: function (newValue) {
      newValue = this.mycall()
      }
      }


      This is very bad for browser performance, because always call request from the browser.



      2) use beforeUpdate or Updated life-cycle:



      updated () {
      this.mycall()
      }


      That works but has bad performance. It makes requests many times to the server.



      3) or that with sockets



      updated () {     
      this.socket.on('user-deleted', function (data) {
      this.mycall()
      })
      }


      and that throws me an error:



      this.mycall() is not a function


      What am I doing wrong?
      Where to put the code with sockets?







      node.js sockets vue.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 17:39









      Vasilis GreeceVasilis Greece

      403321




      403321
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I have changed the view all users file to:



          ...
          methods: {
          mycall () {
          axios.get('http://localhost:7000/api/users')
          .then(res => {
          const data = res.data
          const users =
          for (let key in data) {
          const user = data[key]
          user.id = key
          users.push(user)
          }
          this.users = users
          })
          .catch(error => console.log(error))
          },
          socketcall (thecall) {
          this.socket.on(thecall, (data) => {
          this.mycall()
          })
          }
          }
          ....
          created () {
          this.mycall()
          },
          mounted () {
          this.socketcall('user-deleted')
          }


          Life cycle-hooks cannot retrieved functions inside "this.socket.on" so I thought to do like above and it works!






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435993%2ffetch-data-with-vue-and-sockets%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I have changed the view all users file to:



            ...
            methods: {
            mycall () {
            axios.get('http://localhost:7000/api/users')
            .then(res => {
            const data = res.data
            const users =
            for (let key in data) {
            const user = data[key]
            user.id = key
            users.push(user)
            }
            this.users = users
            })
            .catch(error => console.log(error))
            },
            socketcall (thecall) {
            this.socket.on(thecall, (data) => {
            this.mycall()
            })
            }
            }
            ....
            created () {
            this.mycall()
            },
            mounted () {
            this.socketcall('user-deleted')
            }


            Life cycle-hooks cannot retrieved functions inside "this.socket.on" so I thought to do like above and it works!






            share|improve this answer




























              0














              I have changed the view all users file to:



              ...
              methods: {
              mycall () {
              axios.get('http://localhost:7000/api/users')
              .then(res => {
              const data = res.data
              const users =
              for (let key in data) {
              const user = data[key]
              user.id = key
              users.push(user)
              }
              this.users = users
              })
              .catch(error => console.log(error))
              },
              socketcall (thecall) {
              this.socket.on(thecall, (data) => {
              this.mycall()
              })
              }
              }
              ....
              created () {
              this.mycall()
              },
              mounted () {
              this.socketcall('user-deleted')
              }


              Life cycle-hooks cannot retrieved functions inside "this.socket.on" so I thought to do like above and it works!






              share|improve this answer


























                0












                0








                0







                I have changed the view all users file to:



                ...
                methods: {
                mycall () {
                axios.get('http://localhost:7000/api/users')
                .then(res => {
                const data = res.data
                const users =
                for (let key in data) {
                const user = data[key]
                user.id = key
                users.push(user)
                }
                this.users = users
                })
                .catch(error => console.log(error))
                },
                socketcall (thecall) {
                this.socket.on(thecall, (data) => {
                this.mycall()
                })
                }
                }
                ....
                created () {
                this.mycall()
                },
                mounted () {
                this.socketcall('user-deleted')
                }


                Life cycle-hooks cannot retrieved functions inside "this.socket.on" so I thought to do like above and it works!






                share|improve this answer













                I have changed the view all users file to:



                ...
                methods: {
                mycall () {
                axios.get('http://localhost:7000/api/users')
                .then(res => {
                const data = res.data
                const users =
                for (let key in data) {
                const user = data[key]
                user.id = key
                users.push(user)
                }
                this.users = users
                })
                .catch(error => console.log(error))
                },
                socketcall (thecall) {
                this.socket.on(thecall, (data) => {
                this.mycall()
                })
                }
                }
                ....
                created () {
                this.mycall()
                },
                mounted () {
                this.socketcall('user-deleted')
                }


                Life cycle-hooks cannot retrieved functions inside "this.socket.on" so I thought to do like above and it works!







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 25 '18 at 11:43









                Vasilis GreeceVasilis Greece

                403321




                403321






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435993%2ffetch-data-with-vue-and-sockets%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Wiesbaden

                    Marschland

                    Dieringhausen