Instantly refresh Vue props array within Axios callback

Today, I have a question that is quite general and simple, so I don't have any specific code to share. The basic steps involved are:

  • Firstly, pass an array as a prop to a child component.
  • Next, within the child component, iterate over the array using v-for.
  • After that, I make an axios post request to update the "user-list" (which is the array). However, Vue doesn't update this array because a prop is not reactive. So, my main query is: How can I use computed properties as passed down props to ensure the array updates in real-time?

Although I don't have much code to show, here's a snippet:

       <div class="users" v-for="participant in part" :key="participant.id">
          <template v-if="participant.name !== username">
            {{participant.name}}
            <span>
              <a style="cursor:pointer" title="kick" @click="kickUser(participant)">

...

  props: ["participants", "username", "channel"],

  methods: {
kickUser(user) {
  axios
    .post("/kickuser", { user: user, channel: this.channel })
    // .then((this.participants = []));
}

The axios post method 'kickuser' removes a user from the database, which in turn reduces the array by one user. I'm hoping someone can assist me with incorporating computed properties.

Answer №1

Assuming certain things here, so there may be adjustments needed as more details are revealed...

Imagine you have a parent component containing data. Here's an example:

data: () => ({ participants: [...] }),

You then transfer this data to a child component like this:

<Child :participants="participants" 
       :username="..." :channel="..."/>

and inside the child component, you execute a task that requires an HTTP request.


After that, you emit an event from the child component like so:

methods: {
  async kickUser (user) {
    let { data } = await axios.post('/kickuser', { user, channel: this.channel })
    this.$emit('kick', data)
  }
}

and catch this event in the parent component:

<Child :participants="participants" @kick="handleKick"
       :username="..." :channel="..."/>
// parent "methods"
methods: {
  handleKick (data) {
    this.participants = [] // or any other necessary action
  }
}

This entire process is explained in Vue's documentation ~ One-Way Data Flow

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

Trouble with AJAX GET request functionality

I am new to AJAX and attempting to make my first AJAX call. Here is the code I have so far: $.get( "validate.php", { 'userinput':'x'}, function(response) { if( response.status ) alert( "Matches found" ); else alert( "No matches ...

Is the performance impacted by using try / catch instead of the `.catch` observable operator when handling XHR requests?

Recently, I encountered an interesting scenario. While evaluating a new project and reviewing the codebase, I noticed that all HTTP requests within the service files were enclosed in a JavaScript try / catch block instead of utilizing the .catch observable ...

Tips for dynamically updating the value of a variable in Vue by importing a JavaScript file

There is a file for an app that imports ymaps.js where YmapsComponent.vue is declared. import '../js/ymaps.js'; import { createApp } from 'vue'; const app = createApp({}); import YmapsComponent from './components/YmapsComponent.vue ...

What is preventing me from using bracket notation with a variable to assign a property to an object?

I am a complete beginner when it comes to Vuex, and I am currently facing an issue with assigning a value to a Vuex state, specifically state.map.status.isReady. To make my code more reusable, I decided to create a function called changeMapStatus(state, k ...

Guide to incorporating animated material icons in vuetify

in Vuetify makes it easy to utilize mainstream material design icons through the use of the v-icon component. An example of this would be: <v-icon>home</v-icon> I am curious if animated material icons are supported and can be integrated in ...

Where should we place the JavaScript reference in our CSHTML file in an MVC framework?

At the beginning of our .cshtml page in our current web application, we have included the following: @using Carwale.UI.PresentationLogic; @model Carwale.Entity.ViewModels.HomeModel @{ ViewBag.CustomJS = "~/Views/StaticPartials/HomeScripts.cshtml"; ...

When sending a request from Vue.js using Axios to PHP, the issue arises that the .value property is

There is a chat box with bb smileys underneath. Clicking on the smileys adds them to the text in the input box. However, when using axios to post, the array is empty. Manually entering the smiley bbcode works fine. <input id="txtName" @keyup.enter="ad ...

Sharing specific props with deeply nested components in React

I am experimenting with configuring props for children components. In this example, I am testing a function to target any child, whether nested or not, with the prop swipeMe. It works perfectly when the render function contains only a single child, like ...

Encountering an issue with Angular 1.6 and webpack: controller registration problem

Currently developing a small application with Angular for the frontend, and my frontend module is structured as follows: https://i.stack.imgur.com/tjfPB.png In the app.js file, the main Angular module 'weatherApp' is defined: angular.module(&a ...

Using incorrect string as JavaScript argument

Currently, I am facing an issue with passing parameters elegantly in my code. I have a link for deleting items which looks like this: <a href="javascript:confirmDelete('${result.headline}', ${result.id});"> The problem occurs when the res ...

Is Vue Facing an Endless Loop Bug?

During my experience with Vue, I came across a scenario that led to an infinite refresh loop. To troubleshoot this issue, I initiated a new vue project (version 2) and crafted the following two simple files. If you remove the comments from {{counter}} in t ...

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

Assign Monday as the selected day of the week in the MUI Datepicker 6

I am currently using version 6 of the material ui Datepicker and I am trying to configure it so that the week starts on Monday. import React from "react"; import { DatePicker as DatePickerDestop } from "@mui/x-date-pickers/DatePicker"; ...

When the user clicks on the element, swap out the current image tag

Is it possible to replace the <img src> code in a textarea with image URLs when a button is clicked? <textarea> <img src="https://example.com/image1.gif" alt="image1" /></a> <img src="https://example.com/image2.gif" alt="ima ...

The focus and blur events for the document in a content editable iframe are not activated by Chrome

As I modify the content of an iframe while it is in focus, I have noticed that this seems to function properly in Firefox. However, I am facing issues as the focus and blur events do not seem to trigger in Google Chrome! var iframe = $('#iframe') ...

Send an object to query when using Router.push in Next.js

Just getting started with NextJs and I'm experimenting with passing an object to another page through a component. Let me show you the code and explain what I'm attempting to accomplish: The object I want to pass looks like this: objectEx = { ...

JQuery Ajax Success does not fire as expected

I am facing an issue with my ajax call where the success function is not getting triggered. My controller gets called and the code executes without any errors. However, since my method returns void, I am not returning anything. Could this be the reason why ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

How to position radio buttons in line with labels containing inline inputs using Vue and Bootstrap

Currently, I am facing an issue with my form containing a radio button group where one of the radio button labels includes another numerical input. The layout is not aligned correctly, and I am struggling to adjust the spacing using CSS. I am unable to gr ...

Issues arising from the event target

What is the reason behind this code functioning successfully only when the alert function is called? The color changes after closing the alert box, but if the line with the alert command is commented out, nothing happens. function setLinkColor(el) ...