Exploring the potential of combining vue.js and django involves integrating action triggers, updating components, and

https://i.sstatic.net/n5RaQ.png

Purpose of vue.js components

  • The main objective of the DataTable component is to display data from the backend database.
  • The primary function of the NewDataPanel.vue component is to add new data to the backend database.

Desired functionality

After creating new data using the NewDataPanel, it should be visible in the backend database as well as in the DataTable component.

Issue at hand

Although new data is successfully added to the backend database, there is a problem with refreshing the DataTable component.

Following the required sequence of methods:

this.$store.dispatch('postResult')
this.$store.dispatch('getResult')

it was expected that newly added data would first be created and then all data would be retrieved from the backend. This should result in a mutation of 'the store' to display the refreshed data in the DataTable component.

However, after adding the first data element, nothing changes in the DataTable. It is only after adding a second data element that the first one becomes visible.

How can I implement DataTable refreshment after adding new data?

P.S.: Sources and components diagram can be found below.

DataTable.vue

export default {
    // ...
    computed: {
        // ...
        ...mapGetters(['resultTable'])
        // ...
    }
    // ...
    beforeMount () {
        this.$store.dispatch('getResult')
    }
}

NewDataPanel.vue

export default {
    // ...
    methods: {
        // ...
        addData () {
            // ...
            this.$store.dispatch('postResult')
            this.$store.dispatch('getResult')
            // ...
        }
        // ...
    }
    // ...
}

The vuex store's actions interact with Django Rest Framework via an API:

  • postResult: sends JSON to the backend for saving data

  • getResult: fetches a list of serialized objects and updates the state.resultTable with that data

vuex' store.js

actions = {
    getResult ({commit}, payload) {
        Result.getResult(payload).then(result => {
            commit(GET_RESULT, {result})
        })
    },
    postResult ({commit}, payload) {
        Result.postResult(payload)
    }
}

Answer №1

It is evident in the code provided that the Result methods are returning promises. It is recommended to also return these promises from your actions. Here is an example:

actions = {
    getResult ({commit}, payload) {
       return Result.getResult(payload).then(result => {
            commit(GET_RESULT, {result})
        })
    },
    postResult ({commit}, payload) {
        return Result.postResult(payload)
    }
}

By using promises, you can ensure that the execution of getResult will only happen after postResult has completed.

this.$store.dispatch('postResult')
.then(() => this.$store.dispatch('getResult'))

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

The fadein feature in Deps.Autorun is not functioning as expected in Meteor version 0.5.9

Here is the code I am currently working with: Template.jobFlash.helpers({ latest_job: function(){ if(Session.get("latestJob")!=""){ return JobsCollection.findOne({}, {sort: {'added_date': -1}}); } } }); Deps. ...

Angular 15: Utilizing the Mat Slider Component for Dynamic Value Adjust

This particular code worked perfectly fine in Angular 14, but unfortunately it seems to have compatibility issues with Angular 15. <mat-slider min="1" max="150" step="10" ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

What is the best way to send a JSON object in Vue.js?

<template> <div id="app"> <div id="bee-plugin-container"></div> </div> </template> <script> // import axios from "axios"; // import Bee from "@mailupinc/bee-plugin"; import $ from 'jquery' ...

The function update in chart.js is not available

I encountered an issue while trying to update my chart. When I clicked the button, an error message popped up saying TypeError: pieChartData.update is not a function const LatestSales = props => { const {pieChartData} = props; const toggle ...

What are the methods to repurpose WriteStream's data in node.js?

For my application, I require numerous white placeholder PNG images in various sizes, but creating them manually is not feasible. To address this issue, I developed a service that dynamically generates these images using the pngjs library. The process wor ...

Is there a way to detect changes in a Service variable within an Angular component?

One of my components contains a button that activates the showSummary() function when clicked, which then calls a service named Appraisal-summary.service.ts that includes a method called calc(). showSummary(appraisal) { this.summaryService.calc(appraisal ...

Specify the versions of packages in your package.json file

My package.json file contains many dependencies with "*" as the version, which I have learned is not recommended. I want to update them all to their latest versions. Despite using npm-check-updates tool, it indicates that all packages are up-to-date. Can ...

Click the "Add" button to dynamically generate textboxes and copy the contents from each

I am working on a project where I have an Add button and 6 columns. Clicking on the Add button generates rows dynamically, which can also be deleted. My challenge is to copy the content of one textbox into another in 2 of the columns. This copying function ...

Sending Node.js FileStream Image to HTML5 FileReader API

Is there a way to utilize Node FileSystem for opening a file and then having it read by the FileReader API? const myFile = "C:\\Users\\Me\\Image.png"; fs.readFile(myFile, (error, data) => { const blob = new B ...

What is the best way to display information using Datatables in VueJs?

The data retrieved from the API is appearing next to the datatable instead of within it. In my Vuex actions, I am fetching an array of records from an API and returning the state (array) through getters to components where datatables are being used. impo ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

How do I navigate to the homepage in React?

I am facing an issue with my routes. When I try to access a specific URL like http://localhost:3000/examp1, I want to redirect back to the HomePage. However, whenever I type in something like http://localhost:3000/***, I reach the page but nothing is dis ...

Display a JavaScript dialogue box containing a PHP variable

Is there a way to display the correct JavaScript box when using a While loop in PHP? Here is the code snippet: while($result= mysql_fetch_array($data)){ <tr class="<?php echo $style;?>"> <td><?php echo $result['commis ...

Activating gzip compression using fetch.js

I am utilizing fetch.js (https://github.com/github/fetch) to transmit a rather substantial JSON object to the backend. The size of the JSON is significant due to it containing an SVG image string. My question is whether fetch.js applies gzip compression a ...

Can you explain the concept of 'each' when using the looping method in jQuery?

I'm grappling with accessing data within a table row. The data could be within a <td> tag, as text in an input field, or as a checkbox in an input field, or even as a button. To illustrate, here's a snippet of a small table: <table bor ...

The operating system MacOS requests permission from the parent Node process rather than the child process

When using the child_process module, I encountered a situation where MacOS prompts for permissions for the parent process instead of the spawned child. For instance, running the code below in the terminal results in MacOS asking for permission for "Termina ...

Extract the image URL from the href attribute using Xpath

My goal is to extract all images enclosed in href attributes from the given code snippet <div class="jcarousel product-imagethumb-alt" data-jcarousel="true"> <ul> <li> <a href="https://domain/imagefull.jpg" onclick="return false;" cla ...

Automated profit/loss prediction using a combination of Django and React

I'm currently in the process of developing an analysis website that utilizes the Yahoo Finance API. models.py class Stock(models.Model): money_to_invest = models.CharField(max_length=100) stock_price = models.CharField(max_length=100) com ...