What is the best way to use axios in Vue 3 to update variables?

Is there a way to dynamically update the example variable {{user.email}} when the user makes changes to the input field? I've already tested the backend functionality using Postman and everything is working fine.

On the frontend, I'm utilizing Vue.js along with Axios. I have set up a form with an update button to submit the request. The new data entered into the input field gets saved in my MySQL database through Sequelize.

How can I implement a dynamic refresh so that the input field reflects the updated value? Are there specific properties that need to be utilized?

<template>

 //component profile//
 <main>
    <div class="container mt-4" v-if="user">
      <div class="row justify-content-center">
        <div class="col">
          <section class="row">
            <div class="col">
              <div class="card color-bg my-3">
                <div class="card-header">
                  <div class="row justify-content-around">
                    <p class="m-1">Hello {{ user.firstname }} !</p>
                  </div>
                </div>

                <div class="card text-center">
                  <div class="text-center">
                    <p>My email: {{ user.email }}</p>
                    <form class="background-style">
                      <div class="form-group">
                        <label class="font-weight-bold" for="change-email"
                          >*Enter my new email*</label
                        >
                        <input
                          type="text"
                          v-model="email"
                        />
                      </div>
                      <div class="form-group">
                        <div class="btn rounded p-1">
                          <button
                            class="rounded p-2"
                            @click.prevent="modifyMyprofil"
                          >
                           Modify my account
                          </button>
                        </div>
                      </div>
                    </form>
                  </div>
                </div>

                <div class="card-body mx-auto">
                  <div class="btn-danger rounded p-1">
                    <button class="rounded p-2" @click="deleteAccount">
                      Supprimer mon compte .
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
    </div>
  </main>
</template>

<script>
import axios from "axios";
import VueJwtDecode from "vue-jwt-decode";

export default {
  name: "ProfilConnect",
  data() {
    return {
      user: {},
      email: "",
    };
  },

  mounted() {
    axios.get("http://localhost:3000/api/profil/", {
      headers: {
        Authorization: "Bearer, " + localStorage.getItem("token"),
      },
    });

    try {
      let token = localStorage.getItem("token");
      let decoded = VueJwtDecode.decode(token);
      this.user = decoded;
    } catch (error) {
      console.log(error, "error from decoding token");
    }
  },
  methods: {
    modifyMyprofil() {
      axios
        .put(
          "http://localhost:3000/api/profil/",
          { email: this.email },
          {
            headers: {
              Authorization: "Bearer, " + localStorage.getItem("token"),
            },
          }
        )
        .then((response) => {
      
          console.log("Status: ", response.status);
          console.log("Data: ", response.data);
          console.log("Email: ", this.email);
        })
        .catch((error) => {
          
          console.error("Something went wrong!", error);
        });
    },

    deleteAccount() {
      axios
        .delete("http://localhost:3000/api/profil/", {
          headers: {
            Authorization: "Bearer, " + localStorage.getItem("token"),
          },
        })

        .then((response) => {
          this.$store.dispatch("logout").then(() => {
            this.$router.push("/");
            console.log(response);
          });
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
</script>

// store/ vuex

export default createStore({
  state: {
    token: localStorage.getItem("token") || "",
    user: {}, 
  },

  getters: {
    isLoggedIn: (state) => !!state.token,
  },

  mutations: {
  

    auth_request(state) {
      state.status = "loading";
    },

    auth_success(state, token, user) {
      state.token = token;
      state.user = user;
    },

    auth_error(state) {
      state.status = "error";
    },
    logout(state) {
      state.status = "";
      state.token = "";
    },
  },

  actions: {
  

    submitLogin({ commit }, user) {
      return new Promise((resolve, reject) => {
        commit("auth_request");
        axios({
          url: "http://localhost:3000/api/auth/login",
          data: user,
          method: "POST",
        })
          .then((resp) => {
            const token = resp.data.token;
            const user = resp.data.user;
            localStorage.setItem("token", token);
            axios.defaults.headers.common["Authorization"] = "Bearer, " + token;
            commit("auth_success", token, user);
            resolve(resp);
          })
          .catch((err) => {
            commit("auth_error");
            localStorage.removeItem("token");
            reject(err);
          });
      });
    },

    logout({ commit }) {
      return new Promise((resolve, reject) => {
        commit("logout");
        localStorage.removeItem("token");
        delete axios.defaults.headers.common["Authorization"];
        resolve();
        reject();
      });
    },
  },
}); *

Answer №1

After receiving the response, make sure to modify the local state.

this.currentUser.email = response.data.email

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

Encountering a "Unable to use import statement outside a module" issue when trying to import react-hook-mousetrap within a Next.js project

Currently experimenting with Next.js but encountering some challenges. Recently attempted to add react-hook-mousetrap and imported it as per usual: import useMousetrap from "react-hook-mousetrap"; However, this resulted in the following error: S ...

Resolving the Issue of Jerky Graphics During HTML5 Canvas Animation

When animating a layer in canvas, the visual quality becomes uneven if there are additional layers present. You can see an example of this by clicking "RUN" on this fiddle: http://jsfiddle.net/Q97Wn/ If I modify this line: opts.percentageIndicator.clearR ...

Issues with Bootstrap's hamburger menu not functioning properly when clicked

Can't seem to get my hamburger button working. I've followed the bootstrap documentation and ensured that Bootstrap and jQuery are in the correct order, but still no luck. Any suggestions on what could be causing this issue? Are my links misplace ...

Utilize a WCF Service with HTML and JavaScript

FILE WebService.svc.vb Public Class WebService Implements IWebService Public Function Greetings(ByVal name As String) As String Implements IWebService.Greetings Return "Greetings, dear " & name End Function End Class FILE IWebServ ...

Issue with Nuxt 3 and .nojekyll file not being effective on Github Pages

I am facing some challenges while attempting to deploy my nuxt project on a github page. I have included the .nojekyll file in the public folder, but even after running generate, files with "_" are still showing up under public/static. https://i.sstatic ...

Enhancing Three.js interaction with the DOM (using linkify.js)

Having trouble making the click event work and linking a sphere with a URL using the latest version of three.js. Here is my code: // Code snippet will be here Any help or suggestions would be greatly appreciated. I'm still new to this! ...

The error message "ReferenceError: express is not defined" indicates that Node.js is

Recently, I started using Nodejs to develop web servers, utilizing the express module. To install it, I used the command: "sudo npm install -g express". However, upon running the program, an error occurred: "ReferenceError: express is not defined ...

The art of manipulating and converting strings

When working on an exercise that involves taking two inputs, whether they are integers or strings, certain challenges can arise. For instance, having to convert integers to strings or vice versa can lead to unexpected results. Even when attempting to input ...

Encountering issues with installing packages while creating a new Angular 9 project

Recently I updated to node version 12.16.1 (LTS) and Angular CLI version 9.0.3. After creating a new project with the CLI, all files in the root folder are generated but it gets stuck during the installation of node packages. Has anyone else encountered t ...

React Router 4 - Optimizing Component Refresh by Remounting Instead of Re-Rendering

I am currently in the process of configuring a React project that utilizes React Router 4 ("react-router-dom": "^4.3.1"). Within this project, I have implemented a SideBar, a NavBar, and the main content section of the application which changes based on th ...

Error: The requested resource, youtube#videoListResponse, is currently unavailable

When attempting to access a YouTube playlist that includes private videos, the bot will encounter an error message. Error: unable to locate resource youtube#videoListResponse Below is the code snippet in question: if (url.match(/^https?:\/\/(w ...

What steps should I take to show a particular set of data upon selecting a checkbox component?

I have a table with a column named status, which can be in progress, pending, or dispensed. https://i.sstatic.net/1mMNQ.png My goal is to filter the data based on the checkbox that is selected above the table. For instance, if I check the "pending" check ...

Encountering the React Native error message "TypeError: Object(...) is not a function" while using react navigation stack

I am currently facing an issue with my react-navigation-stack. My suspicion lies in the dependencies, but I am uncertain whether that is the root cause. The objective at hand is to create a text redirecting to another page. If there is any irrelevant code, ...

The validation for the number input step in HTML does not function properly when using the value property

Currently working on a form that requires users to input numbers with up to two decimal points, such as valid money amounts. Utilizing Next.js (React) as the JavaScript framework for this project. Encountered an issue where entering a number with more tha ...

Tips for turning off automatic retries in Nuxt 3 when utilizing useFetch

Struggling with the useFetch composable in Nuxt 3, I am facing an issue. I need the request to be triggered only once regardless of the result. Unfortunately, I haven't been able to figure out a way to achieve this. It keeps retrying when the request ...

Designing Interactive Circular Dates on Website

Currently, I am working on a webpage using HTML, CSS, JavaScript, and PHP. The goal is to design a page that features 7 circles representing the current date and the next 6 days. Users should be able to click an arrow to navigate to the following 7 days. ...

Switching individual items created by a v-for loop in Nuxt.js

I am struggling to create a simple accordion-like structure with the ability to toggle individual elements: <div v-for="qa, j in group.questions_answers" :key="j"> <div class="question" @click="toggle()" & ...

Updating JSON data post XMLHttpRequest call

Currently experiencing a puzzling moment. I'm attempting to insert more information into my object after retrieving it from an external source (just for testing purposes, I intend to add random values). Without further ado: As an example, here is w ...

Access Images from Server using Front-End Technology

I have a collection of images stored in a server folder that I want to display on a div element using client-side code. Initially, I tried to achieve this with AJAX, but it returned raw data instead of the image URL. Despite my efforts to find a solution, ...

Challenges when using deep linking to URL with AngularJS ui-router

Recently, I encountered an issue after restructuring the folder organization of my AngularJS application. Although I believe this might be a distraction from the root cause, I moved a section of functionality to its own directory for better organization. A ...