0
votes

Maybe you can help me. I searched and tryied lot of things.

I have a Nuxtjs project with Laravel 5.7 API (JWT Auth for the auth). A user can CRUD a post. Everything works or almost. When the current user create a post, after he is redirected on the page where his posts are indexed. But sometime the new post created appear and sometimes not, I have no error in console logs and server-side the created post is present in database. When I refresh the page, the new post renders. It's very random. Same thing for the delete action.

I use NuxtJs with Vuex for store. I call the action in my component method with dispatch. The action call axios put or delete method and I commit a mutation to update the state.posts array. after dispatch I refetch the user with auth module of NuxtJS to reload the user's posts. and push the route.

Just below the implementation of the delete action to show you my logic.

My component method :

deletePost(post) {
  this.$toast.show('Do you really want to remove this post ?', {
    duration: 5000,
    icon: 'check',
    action: [
      {
        text: 'No',
        onClick: (e, toastObject) => {
          toastObject.goAway(0)
        }
      },
      {
        text: 'Yes',
        onClick: (e, toastObject) => {
          this.$store.dispatch('posts/deletePost', post).then(() => {
            console.log('here')
            this.$auth.fetchUser()
            this.$router.push({ path: '/:account/posts' })
          })
          this.$toast.show('Post successfully removed', {
            icon: 'check'
          })
          toastObject.goAway(0)
        }
      }
    ]
  })
},

The store action :

deletePost({ commit }, post) {
    this.$axios
      .delete(`/posts/${post.id}`)
      .then(res => {
        console.log(res.data)
        if (res.data.message === 'success') commit('DELETE_POST', post)
      })
      .catch(err => {
        console.log(err)
      })
  }

The store mutation :

DELETE_POST(state, post) {
    const index = state.posts.findIndex(item => item.id === post.id)
    state.posts.splice(index, 1)
  }
1

1 Answers

0
votes

When your are adding or deleting properties of a reactive object, you have to make sure the view updates accordingly. So I think you have to use Vue.delete and Vue.set properties. Please refer https://vuejs.org/v2/api/#Vue-delete and https://vuejs.org/v2/api/#Vue-set

When you are deleting a post from a posts list, your posts list view should be updated accordingly

Edit your DELETE_POST mutation as follows,

DELETE_POST(state, post) {
    const index = state.posts.findIndex(item => item.id === post.id)

    if (index > -1) {
        Vue.delete(state.posts, index);
    }
  }

Also when you are updating a property of a post do your mutation as follows,

UPDATE_POST(state, updatedPost) {

    let index = state.posts.findIndex(post => post.id === updatedPost.id);

    if (index > -1) {
           Vue.set(state.posts, index, updatedPost)
    }
 },