Vue: updating data on the server by sending it through an axios.put request

Managing user account information is a key feature of my application. Users have the ability to edit their details by simply clicking on the edit button, which triggers two different containers to display depending on whether the edit mode is activated or not.

However, I am encountering issues when trying to save and update the user information through the API. The following snippet illustrates part of the code:

<div class="col-4">
    <button
      @click="savePatient(user)"
      type="button"
      class="btn btn-success float-end"
    >
      <i class="fas fa-save"></i>
      Save
    </button>
</div>
<hr />
<div v-if="userdetails">
  <div class="form-group row text-left">
    <label class="col-md-4 col-form-label">
      <strong>Email Address: </strong>
    </label>
    <div class="form-group">
      <input
        type="email"
        class="form-control"
        id="email"
        v-model="userdetails.patient_email"
      />
    </div>
  </div>

In this section, users can view and modify their email address (userdetails.patient_email) before saving the changes by clicking the 'Save' button. However, I am uncertain about how to pass this updated information to my patient.module.js file in order to perform a PUT request to the API endpoint.

My patient.module.js file includes the following logic:

actions: {
  edit({ commit }, patient) {
    commit("editPatient", patient);
  },
...

mutations: {
  editPatient(state) {
    return axios.put(
      `http://URLv1/patients/${this.id}`,
      {
        patient_email: user.email,
        patient_location: user.location,
        patient_specialties: user.specialty,
        patient_attributes: user.attribute,
        patient_languages: user.language,
        patient_preferred_gender: user.gender
      }
    )
  }
},

Answer №1

When utilizing the axios function, all you need is an action to call it into action.

state: {
   user: {
      email: '',
      location: '',
      specialty: '',
      attribute: '',
      language: '',
      gender: '',
   }
},
actions: {
   editPatient({state, commit}, patient) {
      axios.put(`http://URLv1/patients/${this.id}`, state.user)
   }
}

Remember to assign the value of email to state.user.email

              
<button
  @click="editPatient"
  type="button"
  class="btn btn-success float-end"
>
  <i class="fas fa-save"></i>
  Save
</button>

...

<div class="form-group">
  <input
    type="email"
    class="form-control"
    id="email"
    v-model="user.email"
  />
</div>

...

<script>
export default {
  computed: {
    ...mapState({
      user: (state) => state.patient.user,
    }),
  },
  methods: {
    ...mapActions("patient", ["editPatient"]),
  },
};
</script>

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

Just started working with React and encountered this initial error message in my project

Welcome to Windows PowerShell! Upgrade to the latest version of PowerShell to enjoy new features and enhancements! PS D:\React> cd textutils PS D:\React\textutils> npm start npm WARN config global `--global`, `--local` are deprecated ...

The error message states, "undefined cannot be used as a function."

For testing purposes, I am running checks on my Service using httpBackend. Specifically, I am focusing on a simple get request that needs to be tested for the response code. However, despite my efforts, I keep encountering this error: TypeError: undefined ...

Using pure JavaScript to trigger a pop-up window upon submitting a form

Struggling with sending form data to a PHP page using radio buttons for poll results display. No luck with passing variables using $_POST or $_GET methods. I've checked both, but still nothing. When I tried printing the arrays on the PHP page: <? ...

Combining NodeJS with PHP: A Seamless Integration

They say NodeJS is perfect for creating real-time chat applications and I'm eager to add a chat feature to my website. Right now, I have the design ready and need to work on the back-end code. However, when I use socket.io + express, things don' ...

What is the best way to incorporate a background image in a Bootstrap tooltip?

I'm having trouble displaying an element with a background-image property within a Bootstrap tooltip. The image is not showing up as expected. <div class="big-panel"> <a href="#" data-bs-toggle="tooltip" data ...

Using AJAX to showcase data from a table in a database using the <select> tag but with an unfinished submit process

I am encountering an issue with my code. When I submit the value in getinv.php, it only returns a partial value. For example, when I click '2016-08-27', it only retrieves '2016'... My question is, how can I ensure that the exact value ...

The error in React's useEffect occurs when trying to access the property 'map' of an undefined value

import { handleResponse, handleError } from "./apiUtils"; const baseUrl = process.env.REACT_APP_API_URL; export function getAllNotes() { return fetch(baseUrl + "/notes", { method: "GET", headers: { 'Accept': 'application/j ...

Incorporate attributes into object properties in a dynamic manner

Currently, I am experimenting with bootstrap-multiselect and my goal is to incorporate data attributes into the dataprovider method. Existing Data Structure: var options = [ {label: 'Option 1', title: 'Option 1', value: ' ...

angular data binding returning the identifier instead of the content

I have been dealing with managed fields retrieved from a web server in the following format: { "fields":{ "relationshipStatus":[ { "fieldId":4, "name":"Committed" }, { "fieldId":2, ...

I'm currently utilizing lint in my Angular 2+ project. Is there a way to arrange the constructor parameters in alphabetical order

I am struggling to organize the constructor parameters in TypeScript while using TSLINT with Angular9. I am looking for a rule similar to member-ordering that can help me sort them effectively. constructor( // Sort these private readonly router: R ...

The Node.js error message reads: "Cannot set headers after they have been sent" while trying to make a post request

Yes, I understand this issue has been addressed multiple times on stackoverflow, but unfortunately, I haven't found a solution that works for me. The problem arises when trying to make a post request on my nodejs server. The error message states &apo ...

What is the solution for the error "Build error occurred ReferenceError: self is not defined" when building a NextJs application?

pages/components/moru-sdk.js // https://libraries.io/npm/moru-web-sdk import { MoruCheckout } from "moru-web-sdk"; function MoruService() { const options = { access_key: "test_9425294388834bdface7d1b58fd538bf67627d9408fe4f258982 ...

Replace the Vue loading spinner with either bars or dots in a Laravel Vue.js project

After following the reference provided below and successfully implementing it in my project, I encountered an issue. I would like to change the loading animation from a spinner to either dots or bars. Currently, I am getting the default spinner as the outp ...

using a variable object to load, access data, and handle errors through mutations

element, I have incorporated two distinct mutations in a single react component: const [get_items, { error, loading, data }] = useMutation(GET_ITEMS); const [add_to_cart] = useMutation(ADD_TO_CART); To streamline and access both components' error, ...

Using an if-else statement in AngularJS

<ng-switch on="MyData.Status"> <p ng-switch-when="2"> <p ng-if="MyData.SomeProp == false"> Message 1 </p> <p ng-if="MyData.SomeProp == true"> Message 2 </p> ...

Use the $router.push method to pass an entire object as a parameter

I am attempting to utilize the $router.push method in order to transfer data from one view to another. Below is an excerpt of the code: let obj = { foo: 'f1', foo2: ['f2'], foo3: { foo4: [], foo5: new Map(), ...

manage dynamic form data in React using Ant Design components

My attempts to work with dynamic forms using React and Ant Design have been challenging. Despite my efforts to find solutions online, I have had no luck. Here is a CodePen link where I have recreated the issue I am facing: https://codepen.io/sethen/pen/Rwr ...

Unable to leverage injected services within a directive's link function

Recently, I attempted to incorporate a factory into an existing directive. As the feature is still in progress and my experience with Angular is limited but my knowledge of JavaScript is strong, I encountered some challenges. While everything seemed corr ...

Having issues with video playback on AngularJS

I've been working on creating a video player with angular js but I'm encountering issues with playing the video. Here's what I have attempted: videoPlayer.factory('controloptions',function() { var controloptions={}; co ...

prompting users in a node.js application

I need help with querying the user multiple times in my Node.js application. Currently, all responses get printed out together and the first response is processed by both functions. I suspect this issue arises from the asynchronous nature of Node.js. Can s ...