How can we access state data in a Vuex component once it is mounted?

My goal is to initialize a Quill.js editor instance in a Vue component once it is loaded using the mounted() hook. However, I am facing an issue where I need to set the Quill's content using Quill.setContents() within the same mounted() hook with data obtained from vuex.store.state.

The problem arises as the component returns an empty value for the state data whenever I try to access it, whether it's in the mounted() or created() hooks. Despite attempting solutions such as getters and computed properties, nothing seems to work.

Included below is my entry.js file, which consolidates all components to simplify the task of assisting me:

Vue.component('test', {
    template: 
    `
        <div>
            <ul>
                <li v-for="note in this.$store.state.notes">
                    {{ note.title }}
                </li>
            </ul>
            {{ localnote }}
            <div id="testDiv"></div>
        </div>
    `,
    props: ['localnote'],
    data() {
        return {
            localScopeNote: this.localnote,
        }
    },
    created() {
        this.$store.dispatch('fetchNotes')
    },
    mounted() {
        // Dispatch action from store
        var quill = new Quill('#testDiv', {
            theme: 'snow'
        });
        // quill.setContents(JSON.parse(this.localnote.body));

    },
    methods: {
        setLocalCurrentNote(note) {
            console.log(note.title)
            return this.note = note;
        }
    }
});

const store = new Vuex.Store({
    state: {
        message: "",
        notes: [],
        currentNote: {}
    },
    mutations: {
        setNotes(state,data) {
            state.notes = data;
            // state.currentNote = state.notes[1];
        },
        setCurrentNote(state,note) {
            state.currentNote = note;
        }
    },
    actions: {
        fetchNotes(context) {
            axios.get('http://localhost/centaur/public/api/notes?notebook_id=1')
                    .then( function(res) {
                        context.commit('setNotes', res.data);
                        context.commit('setCurrentNote', res.data[0]);
                    });
        }
    },
    getters: {
        getCurrentNote(state) {
            return state.currentNote;
        }
    }
});

const app = new Vue({
    store
}).$mount('#app');

Below is the index.html file where the component is rendered:

<div id="app">
    <h1>Test</h1>
    <test :localnote="$store.state.currentNote"></test>
</div>

I have even tried using the props option as a last resort, but unfortunately, it did not provide a solution. Apologies for the lengthy question. Thank you for your time in reading this. Have a wonderful day! ;)

Answer №1

To address the issue with the code above, I suggest following these debugging steps:

  • Utilize Vue dev tools to confirm if the states are being properly set after the network call
  • Since data is being fetched asynchronously, it's possible that the data has not been retrieved by the time the created/mounted hook is invoked.
  • Include an updated hook in your component to track and access the state for verification.

Once you have conducted the debugging process as outlined, please share the outcomes so that I can provide further insights.

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

Utilizing jQuery to automatically populate fields in an Android WebView when loading a URL

I have been able to achieve the desired output by using the following code in JS: mWebView.loadUrl("javascript:{document.getElementsByName('emailaddress')[0].value = '"+username+"'; document.getElementsByName('password')[0].v ...

Receiving an error message when attempting to host Vue on a subdomain: Uncaught SyntaxError due to an unexpected token '<

I am encountering an issue with my two Vue apps that are basically clones of each other but deployed on the same server (Ubuntu/Apache). The first app is located on the root domain, such as https://example.com Whereas the second app is on a subdomain, fo ...

Having trouble installing gatsby-plugin-transition-link using npm

https://i.stack.imgur.com/DyZxQ.png I'm facing some issues while trying to install gatsby-plugin-transition-link using npm. No matter what solutions I've attempted, the errors persist. Can anyone provide insight into what might be causing this p ...

The map feature is not working on the imported Obj file

After my previous question here, I'm attempting to give each side of this obj a different texture. However, despite applying everything in the correct order, nothing is showing up and there are no console errors. It seems like a simple task but I&apo ...

What is the best way to transfer all li elements with a certain CSS style to a different ul?

I have a task to relocate all the <li style="display:none;"> elements that are currently nested under the <ul id="bob"> into another <ul id="cat">. During this relocation process, it is important that all the classes, ids, and CSS style ...

Use a boolean value to determine the styling of multiple items simultaneously

I'm currently attempting to modify the appearance of the bars in each area (a total of 12), so that a value of 1 equates to true (displayed as green) and a value of 0 equates to false (displayed as red). This will dynamically change the color of each ...

Exploration of features through leaflet interaction

Attempting to plot bus routes on a map using leaflet with geojson for coordinates. Facing issues with making the bus line bold when clicked, and reverting the style of previously clicked features back to default. Current Progress function $onEachFeature( ...

Getting the css property scaleX with JQuery is as simple as executing the

I am struggling to print out the properties of a specific div element using jQuery. My goal is to have the different css properties displayed in an information panel on the screen. Currently, I am facing difficulties trying to show scaleX. Here is my curr ...

The resume button is failing to activate any functions

I recently encountered an issue with a JS file that is associated with a Wordpress Plugin, specifically a Quiz plugin featuring a timer. I successfully added a Pause and resume button to the quiz, which effectively pauses and resumes the timer. However, I ...

Having difficulty with loading images lazily in a jQuery Mobile app with LazyLoadXT feature

Struggling to incorporate lazy loading in my jQM app with Lazy Load XT v1.0.6. Oddly, images only appear when switching browser tabs, not while scrolling down. This happens on Firefox and Chrome. <img src="/img/default-img.jpg" data-src="/img/product/ ...

Using Vue.js: Load component only after user's button click

I need some help with my code setup. I want to make it so that the components "dataPart1' and "dataPart2" are not loaded by default, but only appear when a user presses a button to view the data. How can I achieve this functionality in Vue.js? var ap ...

The json_encode() function yields an empty result

I am facing an issue with a PHP script that is supposed to parse an array using the json_encode() method, but it returns a blank output. Here is the PHP code snippet: $companies = $db->getCustomerNames(); print_r($companies) if (!empty($companies)){ $ ...

The ng-repeat in the inner loop is excluding the initial element of my array and subsequently placing them in the final HTML tag

I am facing a challenge with converting a JSON array into HTML using angular's ng-repeat. The JSON structure I'm working with looks like: data:{ thing_one:[{ id:1, fields:[{ .... }] }, { id:2, fields:[{ .... ...

Is it possible for a function parameter to utilize an array method?

Just starting to grasp ES6 and diving into my inaugural React App via an online course. Wanted to share a snag I hit along the way, along with a link to my git repository for any kind souls willing to lend a hand. This app is designed for book organization ...

Navigating with Express 4

Currently, I am in the process of implementing Passport for user signup by referring to this helpful guide: https://scotch.io/tutorials/easy-node-authentication-setup-and-local Overall, everything is functioning properly except for one issue - after a su ...

Access a PHP file using XMLHttpRequest to run additional JavaScript code

My main page, referred to as Main.php, contains a button that triggers the display of results from Results.php within a div (divResults) on Main.php. The HTML content "These Are The Results" returned by Results.php is successfully displayed in the divResu ...

Trigger a new tab opening following an ajax response with Javascript

Having trouble opening in a new tab after receiving an ajax response with JavaScript, I attempted using both _newtab and _blank However, neither of them seem to be working. I wonder, Is there a solution available to find the answer? ...

Decoding the `this` Mystery in VueJS

Recently, I decided to delve into the world of VueJS starting from square one. Following their official guide has been a helpful resource, but I've hit a roadblock at this section. One particular example in the guide caught my attention... var app5 = ...

Utilize the fetch function within the useEffect hook to generate a new

How can I effectively implement a component using useEffect? useEffect(() => { fetch('https://website') .then((res) => res.json()) .then((data) => { setData(data) // Utilize fetched data t ...

Hiding a div with Javascript when the Excel dialog box is loaded

I have a piece of JavaScript code that is activated when the user clicks on an excel image. $("#excel").on("click", function () { $('#revealSpinningWheel').reveal(); $(window).load(function () { $('#revealSpinningWheel').hide ...