0

I'm building a website with VueJS and AdonisJS, and I'm setting up a possibility to publish or unpublish an article just by setting the draft attribute to true or false.

This attribute edition is possible from the index, where all the articles can be seen. I made a table where there's an action button that would toggle the attribute, which would send an HTTP POST request to Adonis with the ID.

My concern is for what comes after: I don't believe that replacing the whole array is the good option, but what should I do instead? I tried the following:

handlePublish (id) {
  this.$axios.post('/post/publish', {id: id}, {
    headers: {
      'Authorization': `Bearer [some token]`
    }})
    .then(response => {
      console.log(response)
      let toDelete = ''
      this.posts.map((post, index) => {
        if (post.id === id) {
          toDelete = index
        }
      })

    this.posts.splice(toDelete, 1)
    this.posts.push(response.data)
 })
 .catch(e => console.log(e.response))
}

But somehow nothing gets update, excepted in the database.

Thank you in advance

2
  • Why are you slicing and pushing the entire post when you can simply update your existing post that is already in the array? I mean you are not changing the data structure, you are simply updating an Object property. On success you simply need to find the post which you have gotten from your response in your posts array and update its draft property. Commented Oct 16, 2018 at 11:54
  • Okay, I didn't know it was possible, I thought that somehow I'd corrupt something, thanks! Commented Oct 16, 2018 at 12:55

1 Answer 1

1

You are using map to iterate over array. Instead you can use map to get updated array by returning the new element in place of old,

.then(response => {
    this.posts = this.posts.map((post, index) => {
        if (post.id === id) {
          return response.data
        }
    })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it works like a charm (and it showed me some mistakes I made, so double thanks!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.