Issue in VueJs where mutations do not properly save new objects to the state

I am facing an issue with updating my vuex store after modifying my user credentials in a component. Below is the code snippet for reference:

 mutations: {
    updateUserState: function(state, user) {
      state.user = user;
    },
}

actions: {
    updateUserData({ commit }, user) {
      commit("updateUserState", user);
    },
}

Inside the component:

    updateUserData() {
      //function to update data in database
      UserService.updateUserData(this.firstName, this.lastName).then(res => {
        if(res.code == 200) {
          this.makeToast('success', res.message);
          //function to fetch current user data post update
          UserService.getUserData().then(res => {
            console.log(res.data);
            //updating my store -> NOT WORKING
            this.$store.dispatch("auth/updateUserData", res.data);
          })
        } else {
          this.makeToast('error', res.message);
        }
      })
    }

Whenever I submit and execute the updateUserData function, my state gets updated instantaneously on the same page (where I have a navbar displaying data from this.$store.state.auth.user;). However, upon switching to another page, the old data from the state (before the update on the previous page) persists... :(

Could someone please point out what might be incorrect here? Appreciate any assistance!

Answer №1

What is the recommended way to access the user instance in your Navbar component? To ensure it stays updated, it's best practice to create a getter in your store file, such as in the auth.js module:

getters: {
    currentUser(state) {
        return state.user;
    },
}

Then, you can use this getter in the computed property of your Navbar component like so:

<script>
    import { mapGetters } from 'vuex';

    export default {
        computed: {
            ...mapGetters(['auth/currentUser'])
        }
    }
</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

Specify that a function is adhering to an interface

Is there a way in Typescript to ensure that a function implements a specific interface? For example: import { BrowserEvents, eventHandler, Event } from './browser-events'; export function setup(){ const browserEvents = new BrowserEvents(); b ...

Is it possible to add a computed value to the bar's end in Chart.JS?

I'm creating a bar graph that has two bars representing different weeks. Currently, it looks like this: https://i.stack.imgur.com/6Avni.png However, I want it to look like this: https://i.stack.imgur.com/TAVqe.png In order to achieve the desired r ...

Having issues with the custom listing feature in Jquery UI auto complete not functioning as expected

I am facing an issue with my implementation of jquery UI autocomplete. The autocomplete functionality is not working as expected, despite the absence of any JavaScript errors. Below is the JSON data that I am working with: {"d":"[{\"label\":&bs ...

Applying a CSS style to a division element

Can I modify the style attribute of a div element using JavaScript? <div style="color:#0000FF"> <h3>This is a heading</h3> <p>This is a paragraph.</p> </div> I am interested in achieving the following: Changing th ...

When the jQuery button is clicked, the execute function will run multiple times

I am attempting to create a button using jQuery that calls a JavaScript function, but I am facing an issue : Upon loading the page, the first click on mybutton does not elicit any response The second click results in the function being executed twice On ...

Implement the TypeScript handleChange function for input fields and dropdown menus

Currently, I am in the process of developing a form using TypeScript and Material-UI components. My objective is to create a change handler function that can be utilized for both select and textfield changes. Below are my state and functions: const [re ...

Instructions on creating a function within the setState() function

This piece of code was created for a React application. The goal is to continuously add a certain number to the state every set interval when the 'AGGIUNGI JACK' button is clicked. However, upon clicking the button, an error message is displayed: ...

The Vue.js reactivity system does not detect changes when a property is updated within a WebRTC callback

Is Vue.js component creation becoming a challenge for you? Imagine creating a small component that requires permissions for the camera and microphone from the user, displaying that stream on a canvas. Sounds simple, right? However, let's face reality ...

What is the reason for the index.html file not connecting to the local .css files and .js file?

I'm currently using node.js to send an .html file that includes the following tags: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="description" content="This is my personal profile website" /> <link r ...

Troubleshooting problem in AngularJS: $http request causing DOM to not update when calling jQuery function

I'm encountering an issue where the DOM is not updating when I make a $http request in a jQuery function call. Please take a look at the Plunker In my code script.js, for testing purposes, I have $scope.components defined both globally and within a ...

Why does it seem like Typescript Promise with JQuery is executing twice?

Figuring out Promises in Typescript/JS seemed to be going well for me, but I've hit a roadblock. I've set up Promises to wait for two JQuery getJSON requests to finish. In my browser, when connecting to a local server, everything functions as ex ...

Updating the Background Image Based on Text Input in JavaScript

Struggling to utilize the text entered into a text input field as a background image URL. Ensuring it is valid is key. This snippet displays what has been attempted so far... CSS: body { margin: 0px; padding: 0px; border: 0px; } .bgimg { backgr ...

Mastering the art of writing protractor scenarios

In a hypothetical scenario where an Angular app consists of two pages - one for contacts (featuring a table with contacts and an "add new contact" button) and another for adding a new contact, the following steps can be outlined: Click on the "add" butto ...

Issue with React Router version 6: displaying an empty page

I am currently grappling with implementing react-router for my react applications. However, I am encountering issues with the routing part as it consistently displays a blank page. Below are snippets of the code from the involved files: index.js import R ...

Illustration of a D3 graph demo

I'm currently working on modifying a d3.js graph example originally created by Mike Bostock. My goal is to replace the d3.csv method with d3.json. I made adjustments to parts of the original code, but unfortunately, my graph has disappeared without an ...

Are all components in Next.js considered client components by default?

I have created a Next.js app using the app folder and integrated the Next Auth library. To ensure that each page has access to the session, I decided to wrap the entire application in a SessionProvider. However, this led to the necessity of adding the &apo ...

How can we determine the remaining balance in the user's wallet after making purchases using JavaScript?

There are three arrays containing data from the back-end, with unknown names or products. The task is to calculate the total amount spent by the user and how much money is left in their wallet. In case the user runs out of money, they can take a loan which ...

Encountering a Prettier error with React Native 0.71 and Typescript

https://i.stack.imgur.com/h9v5X.pngThe app runs smoothly, but these red warnings are really bothering me. How can I resolve this issue?https://i.stack.imgur.com/NebzJ.png ...

Exploring the concepts of nested If statements, for loops, and else if ordering within Javascript programming (FreeCodeCamp - lookUpProfile)

Currently tackling Free Code Camp's Javascript tutorials and encountering a roadblock on the "Contact Profile" <a href="https://www.freecodecamp.com/challenges/profile-lookup#?solution=%2F%2FSetup%0Avar%20contacts%20%3D%20%5B%0A%20%20%20%20%7B%0A%2 ...

Button to expand or collapse all sections in Ant Design Collapse component

Is there a way to create a button that can expand or collapse all tabs in an ant.design Collapse component? I attempted to modify defaultActiveKey but it seems like this can only be done during page rendering. If possible, could someone share a code snip ...