Issue with array filter not functioning correctly upon page refresh when utilizing vue-router

I have a method (shown below) that functions perfectly when I'm directed from a <router-link>.

selectedSpaceObj() {
                if (!this.selectedSpace) {
                    return {};
                } else {
                    return this.spaces.filter(aSpace => aSpace.id === this.selectedSpace);
                }
            }

However, upon refreshing the page or directly accessing the link, it stops working. Even though I can confirm that this.selectedSpace still has a value after the refresh. If I am routed to this page with a parameter of 1 and the URL is myspaces/1, I store this value in selectedSpace. However, upon refresh, I receive an empty array or some strange form of an array. This shouldn't be happening, does anyone know how to resolve this issue?

The rest of my code looks like this: routes.js contains these two paths:

{
    path: '/myspaces',
    name: 'myspaces',
    component: MySpaces
},

{
    path: '/myspaces/:spaceID',
    name: 'returnToSpaces',
    component: MySpaces,
    props: true
}

The idea behind this setup is that I pass the spaceID via a <router-link> from one page to another, which works as expected. The spaceID gets passed correctly.

Room.vue - features a router-link to MySpaces.vue

    <router-link :to="{ name: 'returnToSpaces', params: { spaceID: spaceID } }">
        <v-btn>
            <h3> Go Back </h3>
        </v-btn>
    </router-link>

When I am on the room.vue and click on the button, it redirects me to the myspaces.vue with the correct link myspaces/1 containing the spaceID. However, if I manually type myspaces/1 instead of being redirected, it fails to work and gives me the error:

Cannot read property 'rooms' of undefined
. This prop is linked to the spaceID, so most likely when I refresh the page, it doesn't link the /1 to the spaceID parameter?

myspaces.vue

<template>
    <v-container>

                    <v-layout>
                        <!-- My spaces -->
                        <v-flex md8 xs12>
                            <v-layout row wrap>
                                <!-- The rooms, allRoomsObj returns all rooms in the space with the id of selectedSpace. -->

                                <v-flex v-for="room in allRoomsObj"
                                        :key="room.id"
                                        xs12
                                        sm6
                                        md6
                                        lg6
                                        :class="{'roomDesktop': !$vuetify.breakpoint.xs, 'roomMobile': $vuetify.breakpoint.xs}"
                                >
                                    <!-- A room -->
                                    <v-card class="card-round">
                                        <!-- Image -->
                                        <v-carousel :cycle="false" hide-delimiters :hide-controls="room.images.length <= 1">
                                            <!--:hide-controls="images.length <= 1"-->
                                            <v-carousel-item v-for="image in room.images" :src="image.src" :key="image.id"></v-carousel-item>
                                        </v-carousel>
                                        <!-- Information -->
                                        <v-card-text primary-title>
                                            <v-layout>
                                                <v-flex xs11>
                                                    <h4 class="roomType"> <router-link :to="{ name: 'room', params: { spaceID: selectedSpaceObj[0].id, roomID: room.id  } }">{{ room.type }}</router-link> </h4>
                                                    <h2> {{ room.name }} </h2>
                                                </v-flex>
                                                <v-flex xs1 hidden-sm-and-down>
                                                    <v-btn @click="selectedRoom = room.id"
                                                           :flat="selectedRoom !== room.id"
                                                           :outline="selectedRoom !== room.id"
                                                           fab
                                                           class="selectRoomBtn"
                                                           depressed
                                                    >
                                                    </v-btn>
                                                </v-flex>
                                            </v-layout>
                                        </v-card-text>
                                    </v-card>
                                </v-flex>
                            </v-layout>
                        </v-flex>

                        <!-- Sidebar -->
                        <v-flex hidden-sm-and-down sm4 lg4 class="sidebarSticky">
                            <v-layout row wrap>
                                <!--1 room details, selectedRoomObj returns 1 room with id of selectedRoom, that is in the space with id selectedSpace.-->
                                <v-flex v-for="room in selectedRoomObj" :key="room.id">
                                    <v-card class="card-round">
                                        <!-- Show only 1 image -->
                                        <v-card-media v-for="image in room.images.slice(0,1)" :src="image.src" height="200px" :key="image.id">
                                        </v-card-media>

                                        <v-card-text>
                                            <!-- Side bar - room name -->
                                            <h2 class="sidebarRoomName"> {{ room.name }} </h2>
                                            <!-- description -->
                                            <p> {{ room.description }} </p>
                                            <!-- overview button-->
                                            <p> <router-link :to="{ name: 'room', params: { spaceID: selectedSpace, roomID: selectedRoom } }">room overview..</router-link></p>

                                            <!-- styles/pins/moodboard -->

                                        </v-card-text>
                                    </v-card>
                                </v-flex>
                            </v-layout>
                        </v-flex>

                    </v-layout>

                </v-container> <!-- End of MAIN CONTENT-->
</template>

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

    export default {
        name: "myspaces",
        props: [
          'spaceID'
        ],
        data() {
            return {
                filterMaxLength: 3,
                selectedSpace: 0,
                selectedRoom: 0
            }
        },
        created() {
            // Default selected space (first in json)
            this.selectedSpace = this.spaces[0].id;
            // console.log("spaces " + this.spaces[0].id)

            if (this.spaceID != null) {
                this.selectedSpace = this.spaceID;
            }

            // Default selected room (first in json)
            this.selectedRoom = this.spaces[0].rooms[0].id;

            // If spaceID is received, change the room to the first room in that space.
            if (this.spaceID != null) {
                var backToSpace = this.spaces.filter(aSpace => aSpace.id == this.spaceID)
                this.selectedRoom = backToSpace[0].rooms[0].id
            }

        },
        computed: {
            // Get 'spaces' from store.
            ...mapState([
                'spaces'
            ]),
            // Grab all the rooms in the selected space.
            allRoomsObj() {
                if (!this.selectedSpaceObj) {
                    return {};
                } else {
                    return this.selectedSpaceObj[0].rooms;
                }
            },
            // Grab the space that with the id that equals to the selectedSpace.
            selectedSpaceObj() {
                if (!this.selectedSpace) {
                    return {};
                } else {
                    return this.spaces.filter(aSpace => aSpace.id === this.selectedSpace);
                }
            },
            // Grab the room in the selected space, with the room id that equals to selectedRoom.
            selectedRoomObj() {
                if (!this.selectedSpaceObj) {
                    return {};
                } else {
                    return this.selectedSpaceObj[0].rooms.filter(aRoom => aRoom.id === this.selectedRoom);
                }
            }
        }
}
</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

Switch back and forth between adding and removing a table row using jQuery

Currently, I am developing a drop-down feature for a table that populates its data using MySQL. The functionality involves creating a new table row below the current one when a user clicks a button. However, instead of generating multiple new rows each tim ...

Issue with JQuery UI Tabs not displaying additional HTML pages in JavaScript

One issue I'm facing is that I added Tabs from JQuery UI on my website. The tab containing paragraphs loads fine, but the tabs linked to other HTML pages (which don't have tabs) won't load. Here is my .js file code and .html code: $(funct ...

Alter the color of a single character using JQuery, all while keeping the HTML tags unchanged

I'm currently working on iterating through the DOM using JQuery in order to change the color of every occurrence of the letter m. Here is what I have so far: $(document).ready(function(){ var m = "<span style='color: red;'>m</span& ...

Show multiple items using v-for in a single textarea

Looking for a solution to display looped values within a single textarea instead of separate textareas. Currently using Laravel and Vue, which is showing the values individually in their own textarea elements. <textarea> <div v-for="(ite ...

Comparing tick and flushMicrotasks in Angular fakeAsync testing block

From what I gathered by reading the Angular testing documentation, using the tick() function flushes both macro tasks and micro-task queues within the fakeAsync block. This leads me to believe that calling tick() is equivalent to making additional calls pl ...

Absolute positioning causes an element's height to increase

As I delve into the realm of typographical animations and seek to calculate the baseline of a font at various sizes, I've stumbled upon a peculiar discovery: It appears that the height values of elements tend to increase in an erratic manner when thei ...

Error Found in Electron webview: Unexpected token causing SyntaxError

While using my Electron application on Windows (no issues observed on Mac), I encountered an error with certain external URLs loaded into a <webview> tag: Uncaught SyntaxError: Unexpected token ... (I suspect it has to do with spread syntax). Findi ...

Can Angular-Material help create a sidenav that toggles on and off?

I am struggling to create a side menu that remains closed by default on all screen sizes and always opens on top of other content. Despite my efforts, it keeps switching at widths over 960px. This is the current code for my menu: <md-sidenav is-locked ...

Switching Div Elements Created by PHP

Utilizing MySQL, I am fetching data to dynamically generate nested div tags in a hierarchical structure. This structure consists of div tags within div tags within div tags, all uniquely identified through PHP-generated ids: <div class="holder"> ...

Generating React components dynamically can bring flexibility and efficiency to the

Looking for a solution to dynamically render different components based on the arguments passed with data. While using regular or React.createElement(Item) works fine, all other options seem to fail. http://jsfiddle.net/zeen/fmhhtk5o/1/ var React = windo ...

Using an external call to trigger the revert method in jQuery UI

My draggable event setup looks like this: $(ids.label).draggable({ containment: ids.wrapper, revertDuration: 100, revert: function(event) { $(this).data("draggable").originalPosition = { top: $(this).data('origionalTo ...

Creating a dynamic SlickGrid spreadsheet - a step-by-step guide

My curiosity has been peaked by the SlickGrid plugin. It caught my attention because of the spreadsheet example, but unfortunately I couldn't get it to work. Is it truly feasible to create a spreadsheet where you can select a range of cells and copy/p ...

Passing an object as an argument for a POST request in axios may not yield the desired results

I'm experiencing an issue while attempting to send a post request in VUE.JS using axios. Within my data, I have the TEST object set up like this data () { return { test:{ name: 'foo', surname: 'bar' } }; }, Here is the method be ...

"ng2-file-uploader necessitates a browser refresh in order to function

I am currently utilizing ng2-file-upload within my Angular 10 project to allow users to upload their photos. The upload process is functioning correctly, but the issue arises when the newly uploaded photo does not automatically appear in the photo list wit ...

Transferring data from local storage to a PHP server using AJAX

My attempt to transfer data from local storage to PHP using AJAX resulted in an error mentioning 'undefined index data'. chart.php <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="t ...

experiencing a problem with the scrollTo() function

I am encountering difficulty in finding the correct X and Y coordinate values to move an image using mouse scroll within a div. I have included my sample code below. I have successfully managed to scroll the image without using a div. Can anyone assist m ...

JavaScript code to retrieve and store data from API endpoints

I am working with a Web API endpoint that provides the location of a URL (). When a button is clicked, this API is called and a URL is returned. The file format could be PDF, Excel, or Word. I am looking for a way to download the file and save it to disk ...

One way to dynamically hide certain fields based on the value of another field is by utilizing AngularJS, Razor, and C# in

Need assistance with AngularJS and Razor. I am a beginner in these technologies and need some help with the following code snippet: <div ng-app=""> <p>Input page number to filter: <input type="text" ng-model="pageNumber"></p> ...

React - Login page briefly appears while loading

Hello, I have built a React application that consists of a Login page, Loading page, and the main app itself. However, there is a small issue where after a user logs in, instead of smoothly transitioning to the Loading page until the data is loaded, the L ...

Issue with the PrimeVue Toast Component: Unable to find the file 'ToastMessage' in the directory */toast

Embarking on a new project with vuejs, I decided to incorporate primevue components. However, my VueJS expertise is still in its early stages. The application utilizes a webpack-based build with vue-loader set up, facilitating the installation of primevue. ...