Error: The function "setCookies" is not found in your Durandal single page application

Currently, I am working on developing a single-page application using Durandal framework.

In my project, I have implemented two important functions. The first function is responsible for saving a Bearer token after the user logs in so that it can be used to make API calls later. The second function is designed to retrieve the saved Bearer token when needed from different pages within the app.

To enhance the functionality, I created two more functions - 'setCookies' and 'getCookies'. 'setCookies' should work alongside 'setToken', while 'getCookies' should be synchronized with 'getToken'.

However, I encountered an issue where my browser displayed an error saying 'Uncaught ReferenceError: setCookies is not defined'.

I would appreciate any insights or suggestions on what might be causing this problem. Below is the relevant code snippet:

define(['durandal/app', 'knockout'], function (app, ko) {
return {
    bearerToken: ko.observable(),
    getToken: function () {
        this.bearerToken(getCookies());
        return this.bearerToken();
    },
    setToken: function (token) {
        setCookies("Bearer", token);
        this.bearerToken(token);
        console.error(this.bearerToken());
    },
    getCookies: function (cookieName) {
        var cookieValue = document.cookie.match('(^|;) ?' + cookieName + '=([^;]*)(;|$)');
        return cookieValue ? cookieValue[2] : null;
    },
    setCookies: function (cookieName, cookieValue) {
        document.cookie = cookieName + "=" + cookieValue;
    }
};
});

Answer №1

Ensure you utilize this.setCookies(), not simply setCookies(). The reason behind this is that the function is within the same object that you are returning.

In this context, this pertains to the current object. You have employed this.bearerToken in your code. Therefore, you must invoke the setCookies() function similarly.

Modify the method like so:

setToken: function (token) {
    this.setCookies("Bearer", token);
    this.bearerToken(token);
    console.error(this.bearerToken());
},

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

Cannot find WoopraTracker within the custom event data

I am currently working on implementing Woopra custom event data upon page load by following their guidelines. I have attempted to push events when the page is ready, however, it keeps returning an error that woopratracker is not defined. Strangely, when ...

After each animation in the sequence is completed, CSS3 looping occurs

I have currently set up a sequence of 5 frames, where each frame consists of 3 animations that gradually fade into the next frame over time. My challenge is figuring out how to loop the animation after completing the last sequence (in this case, #frame2). ...

Automatically close the popup each time it is displayed (using jQuery/JavaScript)

I am having issues with auto-closing my popup each time I open it. The current code I have only closes the popup the first time, requiring me to refresh the browser in order to auto-close it again. Can someone please assist me in writing a new code that ...

The ajax function in jQuery seems to be failing to retrieve data from a webmethod

I have created a jQuery function that is triggered by a DOM event: function CalculateAdhesiveWeight(volatiles1, volatiles2, testedWeight) { var volatiles1 = $('#form-textVolatiles1').val(); var volatiles2 = $('#form ...

Developing custom functions in ejs for individual posts

In my blog, I have a feed where all users' posts are displayed dynamically using ejs. There is a comment section that remains hidden until the user clicks the comments button. Below is a snippet of my ejs file: <% posts.forEach(post => { %> ...

What is the process for updating information in Vue.js?

I need assistance with displaying the updated data in a modal. When I trigger the testing(data) function through a click event, the data appears correctly within the function. However, the template does not update and still shows the previous data. How can ...

What is the best way to load a partial in Rails asynchronously with AJAX?

I am currently using the following code to load a partial when I reach the bottom of a div containing a table: $(document).ready(function () { $("#pastGigs").scroll(function () { if (isScrollBottom()) { $('#pastGig ...

Search through an array, identify duplicates, and transfer them into a separate array

I am working with an array of objects containing dates and I am looking to extract objects with the same date values into a new array. Below is the code snippet. var posts = [ { "userid": 1, "rating": 4, "mood": "happy", "date": "2 ...

creating a dynamic loop based on an object's key in javascript

Searching for items in a list can be challenging, especially when hardcoded values are used. handleSearch = e => { const q = e.target.value if(q){ const filtered = this.state.data.filter(o => { return Object.values(o).some(val ...

Looking for tips on resolving issues with the bootstrap navigation bar?

Check out this code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport ...

What to do while waiting for MySQL query in an asynchronous function?

Having an issue with my asynchronous function that queries the database using the mysql library. It seems like the function is not waiting for the query to complete before moving on. Here's the code snippet: async (eventName, eventArgs, app) => { ...

Vue JS encountering issues in rendering method's returned data on DOM

HTML Template <div class="item" v-for="n, index in teamRoster"> <span> {{ getFantasyScore(n.personId) }} </span> </div> Function getFantasyScore(playerId) { if(playerId) { axios.get(config.NBLAPI + config.API.PLAYE ...

Utilizing functions for object creation in JavaScript

Having trouble with creating a function that automatically generates an object and then alerts its properties. Can't seem to get the alerts when I click the button. Any assistance would be appreciated. <html> <head> <s ...

passing a variable from PHP to JavaScript

When I attempted to transfer variables from PHP to JavaScript, I found myself quite confused. It was straightforward for me to retrieve values using an ID, like this: var name = $("#name").val(); However, my question is if I want to convert a variable li ...

Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state ...

Use of absolute positioning resulted in the disappearance of the element

Can anyone assist with resolving the issue I am encountering? I currently have three nested divs as follows: <div class="section"> <div class="parent"> <div class="child"> Some random text. </div> </div> </div> To adj ...

JavaScript or HTML can be used to store external embed PDF files in a cache

I have a PDF file from an external source embedded on this page. Although it displays correctly, I am concerned about the file being downloaded each time the page is visited. Would using an object tag instead help to cache the PDF and prevent repeated do ...

Customize your error messages in AJAX requests

The form on my index.php page submits to process.php, triggering the execution of the code below: $(document).ready(function() { $('#login_button').click(function() { event.preventDefault(); var formData = { 'email' ...

What steps can I take to combine the values from an array of dictionaries?

Here is my current data: a = [{"country":"Colombia","date":"1995"}, {"country":"China","date":"1995"},{"country":"USA","date":"1992"}] ...

Tapping into the space outside the MUI Modal Component in a React application

Can Modal Component in MUI be used with a chat bot? When the modal is open, can users interact with buttons and inputs outside of it? How can this be implemented? I want to be able to click outside the modal without closing it. Modal open={open} onClo ...