What is the best method for transferring updated data from the frontend to the backend without needing to store any unchanged values?

After importing a list from a database using axios and storing it in a variable called tasks, each object may resemble the following structure:

tasks: [
    { title: 'some text here' },
    { completed: false },
  ]

If there are 2000 or 3000 of these objects, on the frontend I create a checkbox for each task that toggles the boolean value of "completed" between true and false.

<li v-for="task in tasks">
      <input type="checkbox" v-model="task.completed">
      <label :for="task.title">{{task.title}}</label>
</li>

To update my database with changes made to these tasks, I use the submit method:

submit(){
    return axiosComponent.updateTask(this.tasks)
  }

The issue arises when clicking on submit as it saves all tasks in the list, potentially causing timeouts due to the large number of objects being processed.

The goal is to modify the submit method to only save data that has been changed. If only two tasks have their "completed" status altered, then only those two tasks should be saved to the database, not the entire list.

I am unsure if this optimization can be solely done on the frontend or if backend modifications are required. Below are snippets of my backend code:

The axios component:

updateTask(tasks){
    return axios.put('task/updateStatus', tasks)
  }

The controller managing axios data:

@PutMapping("/updateStatus")
    public void updateStatusOnTask(@RequestBody List<TaskEntity> taskEntities){
        taskManager.updateTaskStatus(taskEntities);
    }

The manager function handling task updates:

public void updateTaskStatus(List<TaskEntity> taskEntities) {
        taskRepository.saveAll(taskEntities);
    }

One approach I tried was creating computed properties to store checked and unchecked tasks separately, and then passing these into the submit method instead of the original "tasks" object:

completedTasks(){
    if(this.tasks){
      return this.tasks.filter(task => task.completed)
    }
  },
  unresolvedTasks(){
    if(this.tasks){
      return this.errors.filter(task => !task.completed)
    }
  },

  submit(){
    return axiosComponent.updateTask(this.completedTasks)
  }

However, the drawback with this method is that the changes are not reflected in the main "tasks" object, ultimately leading to values being overwritten once the page is reloaded. Additionally, if there are many unresolved tasks, saving changes to them could still result in timeout issues.

Answer №1

After receiving the tasks from the API, it is possible to transform them into a different structure like the following.

const tasks = [{ title: "insert text here", completed: false }];
const modifiedTasks = tasks.map((task) => ({ ...task, updated: false }));

The updated attribute will be toggled to true when the checkbox is changed.

<ul v-for="task in modifiedTasks">
  <input
    type="checkbox"
    v-model="task.completed"
    @change="task.updated = true"
  />
  <label :for="task.title">{{ task.title }}</label>
</ul>

Then filter the modifiedTasks and send only the updated tasks back to the API.

sendUpdates() {
  return axiosInstance.updateData(modifiedTasks.filter((task) => task.updated))
}

Answer №2

To meet this requirement, you can easily accomplish it by creating a duplicate of the original array and then comparing the stringified version of the modified object with the cloned one upon submission.

Check out this Live Demo :

new Vue({
  el: '#app',
  data: {
    tasks: [
      { title: 'Title 1', completed: false },
      { title: 'Title 2', completed: false },
      { title: 'Title 3', completed: true },
      { title: 'Title 4', completed: false },
      { title: 'Title 5', completed: true }
    ],
    clonedTasks: []
  },
  mounted() {
    this.clonedTasks = structuredClone(this.tasks);
  },
  methods: {
    submit() {
      const updatedTasks = this.tasks.filter(obj => {
        return !JSON.stringify(this.clonedTasks).includes(JSON.stringify(obj))
      });
      console.log(updatedTasks);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <li v-for="task in tasks">
    <input type="checkbox" v-model="task.completed">
    <label :for="task.title">{{task.title}}</label>
  </li>
  <button @click="submit">Submit</button>
</div>

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

What is the process for computing two input values and placing the outcome in a different input field using Vue.js?

Check out my input fields below: <input v-model="form.sale_quantity" @change="computed" type="number" class="form-control" name="sale_quantity" id="sale_quantity" placeholder="Quantity&quo ...

Deleting a specific row within a Material UI DataGrid in Reactjs: Tips and tricks

As I embark on this React project, things are progressing smoothly. However, a challenge has arisen. The functionality I aim for is as follows: When the checkbox in a row is clicked, I want that particular row to be deleted. For instance, selecting checkb ...

I'm uncertain about how to preview the Nuxt3 application that I've generated

After creating a Nuxt3 in static mode, I want to preview it without having to push it to Netlify every time. My nuxt.config.js remains unchanged: import { defineNuxtConfig } from 'nuxt' export default defineNuxtConfig({ }) However, when trying ...

Executing the FindNow button click using Selenium WebDriver

<div id="queryButton_ns_033T372D9A50ZCTW273X_1889_" style="display:inline-block text-align:center;"> <input type="image" alt="Click Here" src="http://g-ecx.images-amazon.com/images/G/31/rcx-gs/abn/button-click-here._V369364970_.png"> Is ...

Nuxt3 encountered a request error for an unhandled 500 fetch failure at the http://localhost:3000/__nuxt_vite_node__/manifest url

Can you help me understand this error? https://i.stack.imgur.com/0FGa4.png Without making any adjustments to my code, the app builds successfully. However, when running it on dev mode, the following error appears: npm run dev I have attempted rebuilding ...

Create a JSON by merging two maps of strings

After examining the JSON String that I was expecting, here is what it looks like: { "startDate": "2013-01-01", "columns": "mode , event", "endDate": "2013-02-01", "selection": { "selectionMatch": "123456789012", "selectionT ...

How can you identify when a Vuetify radio button is re-selected?

Currently, I am developing a wizard that involves triggering navigation when a radio button is selected. Users should also be able to go back and change their previous choices. However, one issue I have encountered is the difficulty in detecting a re-selec ...

Error: java.lang.IllegalStateException - The path to the driver executable must be specified using the webdriver.chrome.driver system property. The similarity does not address this issue

As I delved into learning Selenium, I encountered an issue while trying to run similar code. Here is what I have: package seleniumPractice; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class seleniumPractic ...

Is it Vue's responsibility to automatically remove all Vue/Vuex watchers when a component is destroyed?

When a component subscribes to Vuex events using this.$store.watch or this.$store.subscribe, is it essential to manually remove the watcher during component destruction, or does Vue handle this internally? P.S: The current setup is based on version 2.6.10 ...

What steps can be taken to resolve the error message "Echo is not recognized"?

Currently, I am handling a project with Laravel 7 along with Vue.js and Laravel-echo. The setup involved installing the Laravel Echo library using npm install --save laravel-echo pusher-js within my application. Additionally, the necessary code was include ...

A Vue button that toggles between three states depending on the value in an array

In my Vue project, I am working on loading an array when the page loads. I need to check the status of each line item in the array and display a specific button for each status using a 3-way toggle. Although I believe I understand the main concept, I am s ...

Troubleshooting Vue Component Visibility Issue in Laravel 5.4 with Passport Integration

Implementing passport using Laravel 5.4 has been a smooth process following the official documentation step by step. All was going well until I reached the "Frontend Quickstart" section. After executing the command to publish the vendor: php artisan vend ...

Vue's keydown event will only fire when elements are in an active state

Encountering a strange issue while attempting to listen for keydown events in Vue.js. The keydown event is attached to a div tag that surrounds the entire visible area: <template> <div class="layout-wrapper" @keydown="handleKey ...

employ identical components in v-if and v-else

Currently, I am in the process of designing a login/register page using Vue. The layout includes separate tabs for both login and registration purposes. Here is a snippet of my template code: <transition v-bind:name="TabEffect"> <div ...

Styling with Radial Gradients in CSS

Struggling to create a banner with a radial gradient background? I'm almost there, but my code isn't matching the design. Any assistance would be greatly appreciated as I can't seem to get the right colors and only part of the first circle i ...

Having trouble configuring the drizzle vue plugin to work with vuejs 2

After following the official documentation for setting up drizzle with vuejs 2 located here, I attempted to run my project using yarn serve. However, during this process, I encountered several errors as shown in the image https://i.stack.imgur.com/hvmnm.jp ...

When executing `npm run start`, a blank page appears exclusively on the server

I recently set up a Vue landing page on my Mac. In the terminal, I navigated to the folder and executed "npm install" and "npm run dev", which ran without any issues. However, when trying to do the same on a managed server, I encountered challenges with t ...

Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...

Vue.js | Web scrapers struggle to track v-for generated URLs

I am currently managing a small website that utilizes Laravel and Vue.js to display a list of items. You can check it out here. It seems like the Google crawler is having trouble following the links generated by the v-for function. In my Google Search Con ...

Tips for leveraging the power of Vuetify in Angular versions 7 and 9

I am looking to integrate Vuetify UI Components with Angular using VueCustomElement. While I have successfully integrated Angular and VueCustomElement, adding Vuetify has resulted in errors such as missing $attr and $. However, I am determined to add eithe ...