Learn how to automatically update data in Vue JS after making a 'POST,' 'DELETE,' or 'PUT' request in Vue JS 2

Whenever I send a 'POST' or 'DELETE' request, the data doesn't update automatically. I have to manually reload the page to see the updated information. Is there an easy way to refresh the data after making any 'POST' / 'DELETE' / 'PUT' request?

What steps should I follow to implement this functionality?

I'm new to working with Vue.js.

Here is the code snippet:

template

// Display list of articles
<b-row>
    <div v-for="article in articles" v-bind:key="article.id">
        <b-card v-bind:title="article.title" img-src="https://picsum.photos/600/300/?image=25" img-alt="Image" img-top tag="article" style="max-width: 20rem;" class="text-left mb-2 mt-4 ml-2">
            <b-card-text>
                {{ article.content }}
            </b-card-text>

            <b-button v-bind:href="'/'+ article.id" variant="primary">See more...</b-button>

            <button class="btn btn-danger btn-sm ml-1" v-on:click="deleteArticle(article)">
                Delete
            </button>
        </b-card>
    </div>
</b-row>

// Create new article form
<div class="mt-5">
    <h2 class="text-left mb-3"> Create new article </h2>

    <b-form @submit.prevent="create" method="post">

        <b-form-group>
            <b-col sm="1">
                <label :for="`type-text`">Title:</label>
            </b-col>
            <b-col sm="9">
                <b-form-input :id="`type-text`" :type="text" v-model="article.title" required></b-form-input>
            </b-col>
        </b-form-group>

        <b-form-group>
            <b-col sm="1">
                <label for="textarea-no-auto-shrink">Content:</label>
            </b-col>
            <b-col sm="9">
                <b-form-textarea id="textarea-no-auto-shrink" placeholder="Write something..." v-model="article.content" required rows="3" max-rows="3"></b-form-textarea>
            </b-col>
        </b-form-group>

        <b-form-group>
            <b-col sm="1">
            </b-col>
            <b-button type="submit" class="mt-2 ml-3">Submit</b-button>
        </b-form-group>

    </b-form>
</div>

script

import axios from 'axios'
export default {
    name: 'List',
    props: {},

    data() {
        return {
            articles: [],
            article: {
                title: '',
                content: '',
            }
        }
    },

    mounted() {
        axios
            .get('http://127.0.0.1:8000/api/')
            .then(response => (this.articles = response.data))
            .catch(error => console.log(error))
    },

    methods: {
        create() {
            axios
                .post('http://127.0.0.1:8000/api/',
                    this.article
                )
                .then(response => {
                    response.data.article = null;
                })
                .catch(error => console.log(error))
        },
        deleteArticle(artcl) {
            if (confirm('Delete ' + artcl.title)) {
                axios.delete(`http://127.0.0.1:8000/api/${artcl.id}`)
                    .then(response => {
                        this.all();
                        return response;
                    });
            }
        }
    },
}

Answer №1

In order to fetch articles only when mounted on the cycle, it is recommended to extract these lines of code into a separate method that can be called whenever necessary.

mounted() {
    this.fetchArticles();
},

methods: {
    fetchArticles () {
      axios
        .get('http://127.0.0.1:8000/api/')
        .then(response => (this.articles = response.data))
        .catch(error => console.log(error))
    },
    create() {
        axios
            .post('http://127.0.0.1:8000/api/',
                this.article
            )
            .then(response => {
                response.data.article = null;
                this.fetchArticles();
            })
            .catch(error => console.log(error))
    },
    deleteArticle(artcl) {
        if (confirm('Delete ' + artcl.title)) {
            axios.delete(`http://127.0.0.1:8000/api/${artcl.id}`)
                .then(response => {
                    this.fetchArticles();
                    return response;
                });
        }
    }
},

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

Tips on preventing right-click actions in jqGrid

While utilizing onSelectRow in a jqGrid, I have noticed that it functions properly when clicking with the left mouse button. However, when right-clicking, it still triggers the function. My aim is for the right-click to perform its usual action (such as di ...

Fulfill the promise once all map requests have been completed

Currently, my focus is on developing a bookmark page that retrieves bookmark results with the respective restaurant IDs. Once the response is mapped, I populate an array with objects. My objective is to ultimately resolve the entire array in order to mani ...

Exploring Data and Models within AngularJS

I am working on a WebApp that has a unique HTML layout Nav-column-| Center Column---- | Right Column Link1---------|Data corresponding|Data Corresponding to Link1-A Link2---------| to Nav-column------| (ie based oon Center Column Link) Link3----- ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...

Vue.js is unable to render the template using Object

During this demonstration at https://jsfiddle.net/ccforward/fa35a2cc/, I encountered an issue where the template could not render and the data in resultWrong remained empty with a value of {} At https://jsfiddle.net/ccforward/zoo6xzc ...

Issue with Bootstrap 3 Modal: Missing Title and Input Labels

I'm currently working on customizing a bootstrap template for my friend's church website. My goal is to create a simple web presence for them, and I am in the process of setting up a contact form. I want this form to appear as a modal where users ...

Using JSP to send variables from an external Javascript file

After creating a timer function, I am looking to display the results on a different page. The setup involves a JSP file calling functions from a separate JS file in order to output the information to another screen: Instructions in the JSP file: <butt ...

Guide on transforming an array object for compatibility with MUI's Autocomplete field

I've encountered a challenge while attempting to transform my incoming object into a format suitable for MUI's Autocomplete component. Here is the current code snippet I am working with: const [contactList, setContactList] = useState([]); useEf ...

Combining Flask with Ajax: AttributeError - WSGIRequestHandler does not have the attribute 'environ'

Currently, I am working on using ajax to trigger the execution of a Python file that continuously monitors changes in a text file. If any changes are detected, it will communicate back to ajax for further actions. The Python script must start running as so ...

Enhancing Accessibility of the 'Return to Top' Link

Currently, I am designing a web page that requires users to scroll extensively. To enhance the user experience, I have included a back-to-top link at the bottom of the page for easy navigation back to the top. This is the HTML markup I have implemented: ...

What is the best way to store data retrieved using a model.find({}) operation?

I am currently attempting to calculate the average value of a collection in my database using Mongoose and Express. The objective is to utilize this calculated value on the "calculator" page when rendering, which is why it is embedded in a post for that sp ...

Implementing a redirect following the notification

I'm facing an issue with a function that sends form data to Google Sheets. How can I make the redirect button work after displaying an alert message? I attempted using window.location.href='', but it redirects without submitting the data. & ...

Achieving a Full-Screen Three.js Canvas in React: A step-by-step guide on spanning the view height and width of a webpage

I've been working on tweaking the code found in this particular example: How to connect Threejs to React? This is the snippet of code I am focusing on: import React, { Component } from 'react' import * as THREE from 'three' clas ...

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

Tips on simulating the Q functions during unit testing in node.js using mocha and rewire!

Struggling with an issue while writing unit tests for node.js. The original code in my file is: var Q=require('q') . . . return Q.all(promises).then(function(data) { _.each(data, function(data) { checking.pu ...

What can you do to ensure Vue detects input element changes after using preventDefault?

In this example, I am trying to prevent a newline from being created in a textarea when the Enter key is pressed. To achieve this, I use the preventDefault method in my event handler and update the value inside the textarea. However, I encounter an issue w ...

"Transforming an array using the map method to generate an object containing arrays optimized for

I'm looking to extract an array of objects from a nested array within JS/React. I attempted the following approach, but it resulted in an error regarding react children - indicating that objects cannot be rendered as children and suggesting the use of ...

Creating an HTML form to collect user data and then automatically saving it to an Excel file stored in a shared Dropbox account

I am looking to extract data from a user form on a website and then automatically save it as an Excel file in a designated Dropbox account once the user clicks submit. Instead of receiving multiple emails every time the form is filled out, I would like t ...

Triggering a function without the presence of an actual event

I need to come up with a solution for reusing a function triggered by an event binding. This problem stems from browsers remembering checkbox states, which is why I have to call the function on document load. One approach could involve wrapping setGrid() ...

Having trouble getting the onclick function to work in order to switch out the images

This is the HTML code that I used Here is the JavaScript code, but the onclick function seems to not be working ...