Home > Mobile >  How do I update my list data when data is already sent in the backend? (VUE/DJANGO)
How do I update my list data when data is already sent in the backend? (VUE/DJANGO)

Time:08-14

I'm new to vue and trying to work it with django. I have a field called status that uses boolean field and set the default=False. I'm trying to update the data in the backend by onclick. When i click the div, data will emit to parent and update the status to !status.

Child:

<div @click="$emit('update-status', this.task)">{{ task.status}} </div>

Parent:

<Task v-for="task in tasks"
      :key="task.slug"
      :task="task"
      :slug="task.slug"
      @update-status="updateStatus"/>


async updateStatus(task) {
 let endpoint = `/api/v1/tasks/${task.slug}/`;
 const response = await axios.put(endpoint, {
       status: !task.status,
 
      });
    }

It updates once and it keeps returning the same value True when I keep on clicking (it should always return opposite of status). I have to manually refresh my browser, so when I click it again it will return False.

CodePudding user response:

If you get your updated object in response, you can simply update your tasks:

Vue.component('task', {
  template: `
    <div @click="$emit('update-status', task)">{{ task.status }}</div>
  `,
  props: {
    task: Object
  }
})

new Vue({
  el: '#demo',
  data() {
    return {
      tasks: [{slug: 'a', status: false}, {slug: 'b', status: false}]
    }
  },
  methods: {
    async updateStatus(task) {
     //let endpoint = `/api/v1/tasks/${task.slug}/`;
     /*const response = await axios.put(endpoint, {
         status: !task.status,
      });*/
      const response = {slug: task.slug, status: !task.status}
      this.tasks = this.tasks.map(t => (t.slug === response.slug) ? response : t)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <Task v-for="task in tasks"
      :key="task.slug"
      :task="task"
      :slug="task.slug"
      @update-status="updateStatus"/>
</div>

CodePudding user response:

Thanks to @Nikola Pavicevic answer

I modified the data to also send it in the backend.

async updateStatus(task) {
      let endpoint = `/api/v1/tasks/${task.slug}/`;
      const data = {
        slug: task.slug,
        status: !task.status,
      };
      const response = await axios.put(endpoint, data);
      this.tasks = this.tasks.map((task) =>
        task.slug === data.slug ? data : task
      );
    
    },
  • Related