When trying to access Ajax fetched data within a VueJS `router-view`, the `$root` object returns undefined only when navigating directly to

As I familiarize myself with vuejs, I decided to challenge myself by creating a webpage similar to an eshop for practice purposes.

My approach involves fetching all the necessary data in a single api call to ensure easy access from all my router-views for categorization.

The current method I employ is fetching the data on the created hook of the new Vue instance and accessing it throughout using $root.

While this method works well in most cases, issues arise when directly navigating to a URL or refreshing the page.

It appears that the category object might not be fully loaded, leading to the return of null.

This seems to be a timing issue, but I have yet to determine the exact placement of components...

My latest attempt at resolving this issue has been through the use of beforeRouteEnter.

Defined Route:

const routes = [
        { path: '/category/:category', component : category}
    ]

    const router = new VueRouter({
        mode: 'history',
        routes: routes
    })

Router View Component:

const category = {
        template: `<div>
                    <h1>{{$route.params.category}}</h1>
                    <b>{{category}}</b>
                </div>`,
        computed: {
            vueRoot: function(){
                return this.$root;
            },
            category: function() {
                    return this.$root.categories.filter(c => c.name === this.$route.params.category)[0]
                })
            },
        }
    }

Main Vue Instance:

var app = new Vue({
        router,
        el: '#app',
        data: {
            products: {},
            groups: {},
            categories: {}
        },
        methods: {
            goBack () {
                window.history.length > 1
                ? this.$router.go(-1)
                : this.$router.push('/')
            },
            fetchProducts: function(){
                $.get("/api/fetchv2.json", function(data){
                    console.log(data);
                    app.products = data.products;
                    app.groups = data.groups;
                    app.categories = data.categories;
                }).fail(function(error) {
                    alert( "error" );
                    console.log(error);
                });
            }
        },
        created: function(){
            this.fetchProducts();
        },
        beforeRouteEnter (to, from, next) {
            this.fetchProducts();
        }
    })

Thank you for your assistance in advance!

Answer №1

When the category component is created, the computed value within it will try to execute. However, since the data is fetched asynchronously from the server, the computed function will attempt to filter an empty object because that's how the 'categories' variable is initially set.

To resolve this issue, make sure to initialize the 'categories' variable with an empty array [] instead.

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

Create a new cookie in Angular if it is not already present

I am looking to check if a cookie is set in Angular. If the cookie is not found, I want to create a new one. Currently, I have this code snippet: if ($cookies.get('storedLCookie').length !== 0) { $cookies.put('storedLCookie',' ...

Incorporate a variable into a string

My task here is to prepend a variable before each specific string in the given text. For example: var exampleString = "blabla:test abcde 123test:123"; var formattedString = "el.blabla:test abcde el.123test:123"; In this case, whenever there is a pattern ...

Embedding a Three.js object within a div element that has disabled zoom functionality and prevents scrolling or zooming within

Recently, I started learning about three.js and currently find myself in need of some assistance. My goal is to set up my scene within a div element rather than the entire document without any zooming while still allowing the user to scroll using the mouse ...

Troubleshooting Appium error management is ineffective

As a newcomer to appium, I might have made some mistakes. I'm encountering a problem with appium while using wdio and jasmine. it('wtf', (done) => { client.init().element('someName').getText() // ^ here ...

To ensure that the first three digits of a phone number are not zeros, you can implement a JavaScript function to validate the input

I've been working on validating a phone number using JavaScript, but I've hit a roadblock. I need to ensure that the area code (first 3 numbers in 999) cannot be all zeros (0). While I know how to create the desired format (like xxx-xxx-xxxx), ...

Converting a text area into a file and saving it as a draft in the cloud with the

Can content from a text area be converted into a file of any chosen format and saved in the cloud? Additionally, should every modification made in the text area automatically update the corresponding file stored in the cloud? ...

Does the Loopback Model have an "exists" method that includes a where clause?

I am interested in querying the data using filters to check for existence. Does loopback support this method of querying? If so, could you provide some guidance? myModel.exists({where: {and: [{city: "London"}, {gender: "F"}]}}, function(err, bool){ if(bo ...

Using the onclick event with an image created through PHP code

I am currently in the process of developing a dynamic image represented as a graph displaying the number of documents generated each day. This interactive image is being created using PHP, and I aim to improve user engagement by enabling them to click on t ...

Unlocking Global Opportunities with Stencil for Internationalization

Hi there, I've been attempting to implement Internationalization in my stencil project but unfortunately, it's not working as expected. I'm not sure what's causing the issue, and all I'm seeing is a 404 error. I followed these arti ...

The $scope variable fails to reflect updates in the view following a broadcast event triggered by a

I have been troubleshooting a similar issue and I can't seem to figure out why the update is not reflecting in the view. While I am able to see the scope variable updating in the catch events logs, the changes are not being displayed in the view. For ...

SPFx WebPart - Tabbed Interface

I am new to developing SPFX WebParts and currently working on creating a Tab WebPart. The HTML appears to be rendering correctly, but I'm facing issues with the Javascript functionality not firing as expected. Any assistance or guidance on how to prop ...

Combining JSON fields and searching based on the combined value within MarkLogic

In the JSON format provided below, I have stored a person's first name and last name along with their nickname. { "Person": { "Records": [ { "nameType": "Primary", "firstName": "Sagar", "lastName" ...

Ways to showcase the chosen image from the input field?

Can someone help me with an issue I'm having regarding displaying selected images? Every time I try, I encounter this error message: Not allowed to load local resource: Any suggestions or insights into why this might be happening? <input type=&a ...

Redirect the Submit button to the specified URL from the form element

Looking for a way to create a form with two fields: Username and Password. Upon clicking submit, the username and password should be added to the URL in a specific format. For instance: The URL structure will remain the same, only the "username_entered_i ...

What is the process for sending data to a node server using POST and receiving a responseText from it through GET?

Here is an example where I'm trying to send data from a JavaScript client to an Express Node server, validate the data against the database on the server, and respond once the verification process is complete. The data object in newHttpRequest.send(da ...

Tips for having <script> update onchange instead of just onload

Is there a way to update the output of the <table id="mortgagetable"> each time a user changes the input values in the form? Currently, it only updates on load. Additionally, the content of the <div id="years" style="display:inline-block;">25 ...

is it possible to dynamically add components within a Vue.js component?

Is there a way to dynamically add components within a component? Note: I do not want these components to be saved globally, but rather added locally. The best way to define the problem is by showing code examples. export default { name: 'tab ...

Eliminate any null strings from an object by comparing the object's previous state with its updated state

I am currently implementing an exemptions scheduler using react-multi-date-picker. The react-multi-date-picker component is integrated within a react-table in the following manner: const [data, setData] = useState(0); const [dateValues, setDateValues] = us ...

Tips to guard against CSRF attacks in an ajax-based application

Looking for advice on protecting against CSRF attacks in an AJAX application. Our setup involves PHP and JQuery, where the main form is loaded initially and subsequent forms are fetched via AJAX requests. For instance, when a user clicks on "customer", t ...

Having trouble running the npm run build command with vue-cli for production builds

Anticipated Outcome Executing npm run build should generate the production-ready dist bundle that can be deployed on a specified device. Current Scenario Despite successful local builds, encountering errors when attempting to execute npm run build on an ...