Is it not possible to apply the .includes method on a string within a v-if directive while utilizing a computed property?

Problem

I am facing an issue while trying to determine if a string contains a substring within the Vues v-if directive. The error message I receive is:

TypeError: $options.language.includes is not a function

The technologies I am using are Vue, Vuex, and Ionic.

The 'language' property is a computed property:

    computed: {
        language() {
            return this.$store.getters.getLanguage;
        }
    }

And here is how the v-if directive looks like:

<ion-label v-if="language.includes('en')">Play as guest</ion-label>

This is what the computed property setup in the store looks like:

    state: {
        language: String,
    }

Mutations:

    mutations: {
        setLanguage(state, payload) {
            state.language = payload;
        }
    }

Actions:

actions: {
        setLanguage(state, language) {
            state.commit('setLanguage', language);
        }
}

Getter:

    getters: {
        getLanguage: state => state.language,
    }

The language property gets its value using the Ionics ionViewWillEnter hook:

    async ionViewWillEnter() {
        const info = await Device.getLanguageCode();
        this.$store.dispatch('setLanguage', info.value);
    }

This method triggers when the component routing into view starts animating.

Attempts made to resolve

  1. I have checked that the computed property is of type string using typeof
<ion-label v-if="typeof language === 'string'">Play as guest</ion-label>

Since the label is displayed, it confirms that the computed property is indeed a string.

  1. I also attempted using indexOf
language.indexOf('en') > -1

However, this resulted in the error:

TypeError: $options.language.indexOf is not a function

At this point, I'm unsure of how to proceed. My goal is to check if the computed property string includes a specific substring within the v-if directive. Any suggestions on how to achieve this would be greatly appreciated. Thank you for your assistance!

Answer №1

The reason behind the issue is that the variable language is defined, but it does not have an includes method, which would typically indicate that it is either an object or a function.

If the condition typeof language === 'string' is true at some point, it suggests that the value of language changes from a non-string to a string during execution.

The core problem lies in this code snippet:

    state: {
        language: String,
    }

Unless this code pertains to component props that utilize special logic for checking prop types and accept constructors for primitive types, assigning String constructor to state.language implies that it is a function.

A better approach would be to set it as:

language: null,

or

language: '',

or

language: 'en',

It's important to note that uninitialized values may require special handling, and using null is preferred as it signifies an uninitialized value and results in clear and unambiguous errors. For instance:

Cannot read property 'includes' of null

Embedding logic into templates is considered bad practice as it complicates debugging, value handling, and can lead to performance issues with complex calculations. This is where computed properties come in handy:

computed: {
    language() {
        return this.$store.getters.getLanguage;
    },
    isDefaultLanguage() {
        return !this.language || this.language.includes('en');
    }
}

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

The Authorization header in POST and PATCH fetch requests is stripped by Typescript

I have developed an API in C# that utilizes JWT tokens for authorization. On the frontend, I store these tokens in local storage and retrieve them when making a request. GET or DELETE requests work seamlessly, as I can verify through console.log() that t ...

Implementing route navigation in two components using a click button

To display the content of the Quiz component with the path "/quiz" after clicking a button and fetching the component with the path "/" is my goal. Here is the code snippet from the App.jsx file: <Router> <Routes> <Route ...

An error occurred while attempting to reset your password on Parse.com (JS SDK) due to an

I am having trouble resetting my password in my angularjs App. I am utilizing Parse (js SDK) as the backend. Even though I am following the documentation and using Parse.User.requestPasswordReset, I keep encountering error 125 which states invalid email ad ...

What is the best way to extract menu and submenu information from an array?

I'm in the process of building a webpage with the help of smart admin and I'm facing an issue with displaying left menu data properly. The data is being retrieved from an array and I need to arrange the menus and submenus based on the parent ID o ...

Executing Node.js child processes: streaming stdout to console as it happens and running the processes one after the other

Details node: v9.4.0 I am looking for a solution to execute external commands sequentially while monitoring the stdout in real-time. The code snippet below demonstrates my attempt to retrieve all test cases from ./test/ and then running them one after ...

What should be triggered when clicking on the cancel button in Bootstrap's modal: `close()` or `dismiss()`?

Bootstrap's modal offers two methods for hiding the dialog: close(result) (Type: function) - Used to close a modal by providing a result. dismiss(reason) (Type: function) - Used to dismiss a modal and provide a reason. Should I use close when the u ...

Issues with the orderBy function are causing unexpected behavior

After creating 3 groups - priority 1, 2, and 3 with orderBy:priorty for each pushed task to go into their designated group, I noticed some strange behavior within the groups where they don't sort properly when more data is added. <input ng-model=" ...

Retrieve data using $http.get when an accordion group is expanded in AngularJS

Currently, I am utilizing Angular v1.2.0rc1 along with Angular-UI Bootstrap. [edit] My objective is to implement a load-on-demand feature with caching while incorporating an accordion functionality. The accordion group that I am using can be found here. ...

Is there a way to modify the CSS or add custom styling within an iframe form?

Currently I am working on the following page: , where an embedded javascript form called infusionsoft (iframe form) needs to be made responsive at the request of my client. I'm wondering if there is a way to override the css or inject custom styles i ...

Error message: "Property undefined when Angular attempts to call a function from jQuery/JavaScript."

I'm currently attempting to invoke an angular controller from my JavaScript code. This is my first encounter with Angular and I must admit, I'm feeling a bit overwhelmed! I've been following this example: Unfortunately, when testing it out ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

Preserve the previous and current state within a React application

Within my code, there is a state called newuser that undergoes changes based on the inputs entered into the input fields. This change occurs once all input fields are filled and the submit button is clicked. The goal I have in mind is to store the current ...

A guide on managing Ngb Bootstrap carousel slide with a button in Angular

I encountered a situation like this: I need to implement a Ngb Bootstrap carousel with buttons for Previous and Next to control the slide images. Clicking on the Previous button should display the previous slide image, and clicking on the Next button shou ...

Using jQuery to extract a specific portion of a URL path

Seeking assistance with extracting category information from lengthy URLs and assigning it to a variable. Consider the following URL: http://example.com/community/home/whatever.html The goal is to assign the variable to the folder path that follows /hom ...

Troubleshooting issue with parsing MySQL data in HTML table using Node.js

Seeking Assistance! I am currently in the process of developing a node file that displays data from MySQL on an HTML page with a search bar. My issue is that sometimes when I run the code, enter something into the search bar and hit the button, it works s ...

If I remove my project but still have it saved on my GitHub, do I need to reinstall all the dependencies or can I simply run npm install again?

I have a question regarding my deleted project that is saved on GitHub. If I formatted my PC and lost the project but it's still on GitHub, do I need to reinstall all the dependencies or can I just run 'npm install'? The project has dependen ...

The strategy of magnifying and shrinking graphs on Google Finance for better analysis and

I am seeking to understand the logic behind a zoom-able graph similar to the one on Google Finance. I am aware that there are pre-made components available, but I am interested in a simple example that breaks down the underlying logic. ...

JavaScript unable to remove cookie from system

I'm currently on an external website and attempting to use JavaScript to remove a cookie. Here's what I tried in the console: function deleteAllCookies() { var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length ...

Svelte is unable to bring in

Hey there, I'm new to Svelte and currently working on a simple feedback app. I have divided my project into two files - one for the main app and another for a list of feedbacks. Here is my App.svelte file: <script> import feedback from ". ...

What is the best way to display multiple values in a single column in a datatable?

This function works effectively in rendering the code: { "data": "assignedTo", "render": function (data) { var btnDetail = "<a href='/Ticket/TicketDetail?ticketI ...