What is the best way to refresh my list information after receiving updated data on the backend? (VUE/DJANGO)

Recently delving into vue and integrating it with django has been a learning curve for me. In my project, there is a field named status that uses a boolean property with a default value of False. My aim is to update the backend data by triggering an onclick event. Upon clicking the div element, the data will be emitted to the parent component which will then toggle the status from True to False or vice versa.

Child Component:

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

Parent Component:

<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,
 
      });
    }

Upon testing, I found that the status updates correctly only once but then keeps returning the same value (True) on consecutive clicks. The desired behavior is for it to always return the opposite of the current status. Currently, I have to manually refresh the browser after each click to see the correct updated status (False).

Answer №1

Upon receiving the updated object as a response, you can conveniently proceed to 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>

Answer №2

Shoutout to @Nikola Pavicevic for the helpful solution!

I made some adjustments to include sending the data to the backend as well.

async updateTaskStatus(task) {
      let endpoint = `/api/v1/tasks/${task.slug}/`;
      const newData = {
        slug: task.slug,
        status: !task.status,
      };
      const serverResponse = await axios.put(endpoint, newData);
      this.tasks = this.tasks.map((singleTask) =>
        singleTask.slug === newData.slug ? newData : singleTask
      );
    
    },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using navigateByUrl() to pass a query parameter

When I click on an icon, I want to navigate to a new page. Here's the code snippet: this.prj = e.data.project_number; this.router.navigateByUrl('/dashboard/ProjectShipment/634'); Instead of hardcoding the query parameter 000634, I need ...

What is the most efficient method for retrieving data upon form submission in Next.js?

When using the provided code and Metadata-scraper to retrieve meta data from a URL, I can do so successfully when it's hardcoded. However, I'm looking for guidance on how to allow users to input a link via a text field and fetch the meta data upo ...

What methods can be used to determine if a bound function is equal when performing unit testing?

I am looking to verify that when I pass an argument to a function, it is indeed a function reference even though the function reference is passed using the bind() method. Take a look at this shortened code snippet that needs to be tested: initialize: fun ...

Utilizing <router-link> in conjunction with vue-custom-element

Recently, I've delved into Vue and am attempting to develop a Vue application that can be integrated into a non-Vue application. To achieve this, I've decided to utilize vue-custom-element. However, I'm encountering difficulties with impleme ...

Guide on how to show the index value of an array on the console in Angular 2

Is there a way to show the array index value in the console window upon clicking the button inside the carousel component? The console seems to be displaying the index value twice and then redirecting back to the first array index value. Can we make it so ...

Adding a fresh HTML element to a list at a designated location

I found this excellent example on CODEPEN Is there a way to insert a new random number into the list so that it appears after 24 but before 19? Is there an efficient solution or do I need to manually check each li element and determine where to place the ...

Exploring and Presenting Arrays using React JS

Recently, I have started working with react js and I am trying to add a search functionality to filter an array in React. My goal is to allow the user to enter a character in the textbox and only see the names that contain that specific character. So far, ...

Can I display different text when blinking with Javascript?

I need to display text that changes every few seconds within a single div. var blink_speed = 1000; // every 1000 == 1 second, adjust to suit var t = setInterval(function () { var ele = document.getElementById('myBlinkin ...

Execute a personalized function when an array is updated or created in JavaScript

I have experience in adding custom properties to objects. For example, if I have a method called foo, const foo = () => { console.log('custom method'); } I can add the foo method to the Array prototype and use it with array variables by Arra ...

Tips for calculating the total of an array's values

I am seeking a straightforward explanation on how to achieve the following task. I have an array of objects: const data = [ { "_id": "63613c9d1298c1c70e4be684", "NameFood": "Coca", "c ...

Displaying/Concealing specific choices using jQuery

Greetings! I am in need of some assistance with my coding query. I have been working on a piece of code where selecting 'x' should reveal another dropdown, which seems to be functioning correctly. However, if I navigate three dropdowns deep and t ...

Vue.js - Inability to Access Data Property

I am facing an issue with my Vue.js 3 app. I am attempting to search through an array of objects within the app. You can find a fiddle showcasing the problem here. The problematic code snippet from the fiddle is as follows: async runSearch() { let search ...

Ways to direct to dashboard if a user is logged in using AngularJS

As a newcomer to AngularJS, I am facing an issue with redirecting my page to the dashboard once the user has logged in. I receive an access token after login, which I save in cookies. Despite trying solutions from Stack Overflow, I have not been able to re ...

Unable to display image using EJS and Multer

While working on my node.js application, I encountered an issue with rendering the uploaded image file. I have successfully integrated multer to handle file uploads, and the images are being stored in the correct folder. However, when trying to display the ...

"Creating a new element caused the inline-block display to malfunction

Can someone explain why the createElement function is not maintaining inline-block whitespace between elements? Example problem First rectangle shows normal html string concatenation: var htmlString = '<div class='inline-block'...>&l ...

Extracting Data from Multiple Pages Using Python 3 without Changing URL

Recently, I delved into the world of web scraping and decided to try my hand at grabbing data from various websites. Currently, I'm focused on scraping information from the site - Using selenium, I've managed to extract longitude and latitude da ...

Tips for updating data in the AngularJS Smart TableWould you like to learn

I'm still getting the hang of Java Script, so please bear with me if this question is a bit basic. Does anyone know how to edit rows in tables using Smart-Table with AngularJS? I can't seem to find any tutorials that match the new version of Sma ...

Utilizing external imports in webpack (dynamic importing at runtime)

This is a unique thought that crossed my mind today, and after not finding much information on it, I decided to share some unusual cases and how I personally resolved them. If you have a better solution, please feel free to comment, but in the meantime, th ...

Implementing user authentication with Python for AWS services

I am currently working on a project involving Python (3.6) & Django (1.10), where I am utilizing AWS APIs. However, being new to AWS, I am unsure about how to authenticate a user for accessing their resources. My scenario is: I require access to the user& ...

Nuxt.js i18n Failing to Display Pages in Default Locale Without Redirecting

I'm currently developing a Nuxt.js project with internationalization (i18n) using the @nuxtjs/i18n module. My goal is to serve pages in French as the default locale without redirecting to /fr/... when no specific locale is provided in the URL (e.g., a ...