Could it be a race condition if the ValidationMixin is lacking a necessary function?

Whenever I try to access my login page, it fails to load due to the following error:

validationMixin__.a.required is not a function

I attempted to simplify the import by changing it to the direct path:

from '@leadlucky/leadlucky-themes/src/mixins/validationMixin.js'

However, the error message still reads as:

leadlucky_themes__.b.required is not a function.

instead of

validationMixin__.a.required is not a function

After investigating, I discovered that the issue lies within the "required" function in validationMixin.js. This file originates from another project of mine which is npm linked (npm link @leadlucky/leadlucky-themes).

Below you will find the validationMixin.js file (containing the "required" method) and the specific code snippet causing problems:

Imgur image gallery

This is the console error being displayed:

The login page should display correctly, but it seems like there could be a race condition where validationMixin.js isn't fully imported before execution. How can I address this issue? It functions properly on all other pages.

Answer №1

After dedicating 5 hours to research, Woo finally cracked the issue. It turned out to be a race condition problem where data() was calling the JS file before it was declared. This was resolved by replacing everything with a const named mixin outside of export default.

Additionally, if you encounter an error stating that VariableName.method('blah') is not a function in your data, try adding a [0] at the end.

 data: function() {

      return {
        username: {value: "", validator: validationMixin.required('Username')[0]},
        password: {value: "", validator: validationMixin.passwordRules[0]},
        passwordConfirm: {value: "", validator: 'x'}
}} 

Here is the updated mixin code:

function buildRules(regExps = [], fns = [], errorMessages = ["Input is invalid"]){
  return [(field) => {
    if(!field) {
      return errorMessages[0];
    }

    let errMessage = null;
    let i = 1;
    regExps.every((exp) => {
      if(!exp.test(field)){
        errMessage = i < errorMessages.length ? errorMessages[i] : errorMessages[0];
        return false;
      }
      i++;
      return true;
    });
    if (!errMessage) {
      fns.every((fn) => {
        if (!fn(field)) {
          errMessage = i < errorMessages.length ? errorMessages[i] : errorMessages[0];
          return false;
        }
        i++;
        return true;
      });
    }

    return errMessage || true;
  }]
}

const mixin = {}
  mixin.emailRules = buildRules(
    [/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/],
    [],
    ['Invalid email']
  );

  mixin.userIdRules = buildRules(
  [/^[A-Za-z0-9]*$/],
  [],
  ['Invalid username']
  );

  mixin.passwordRules = buildRules(
  [],
  [
    pwd => pwd.length >= 8,
    pwd => /.*[A-Z].*/.test(pwd) && /.*[a-z].*/,
    pwd => /.*[0-9].*/.test(pwd),
    pwd => /.*[!@#$%^&*()\-_=+[{}\]| /\\.,<>`~'";:?].*/.test(pwd)
  ],
  [
    'You must create a password',
    'Password must be at least 8 characters',
    'Password must contain upper and lowercase letters',
    'Password must contain a number',
    'Password must contain a special character',
  ]
);

mixin.required = (fieldName) => buildRules([],[],[`${fieldName} is required`]);

mixin.checkedRule = (message) => buildRules([],[],[message]);

mixin.passwordsMatch = (originalPassword) => buildRules(
  [],[(validatePassword) => validatePassword === originalPassword],
  ['Passwords must match']
);

mixin.urlRule = buildRules(
  [],
  [(url) => {
    if(url.toLowerCase().startsWith('http://')){
      url = url.substring('http://'.length)
    }
    if(url.toLowerCase().startsWith('https://')){
      url = url.substring('https://'.length)
    }
    return /[A-z|0-9]+\.[A-z|0-9]{2,22}/.test(url)
  }],
  ['Invalid URL']
);

mixin.pageIdRule = buildRules([/^[A-Za-z0-9]*$/], [], 'Invalid Page Id')

export default mixin

Finally, to workaround the issue, the JS file needed to be included as a mixin rather than a component or directly used.

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

Variations in syntax within TypeScript

I recently began delving into typescript and stumbled upon a unique way of defining the type of an argument. function postThread({userId}:{userId:string}) { // implementation code here } As opposed to the usual method shown below: function postThread({u ...

Can we determine which component is triggering a Vuex action?

Can you determine which component triggers a Vuex action? In my Vuex actions, I return a promise and make decisions in the component by setting error messages on specific fields. However, I want to set these errors on component.$validator.errors as soon a ...

Using Vuetify to highlight selected radio buttons in an edit form

One issue I am encountering involves editing a table row. After clicking on the edit button, a form pops up with the data pre-filled for editing purposes. However, the radio button selected previously does not display as checked in the form; both options a ...

Create a feature that allows users to view photos similar to the way it

I want to incorporate a Twitter feed on my website that displays images posted. Instead of having the images redirecting users to Twitter when clicked, I would like them to reveal themselves underneath when a link labeled "View Photo" is clicked, and then ...

How to restart a setInterval loop in JavaScript

Recently, I created my own version of the "10 PRINT" project to enhance my JavaScript skills. As a finishing touch, I decided to incorporate sliders that would allow viewers to adjust various parameters and witness the impact it has on the project. You c ...

What are the steps for generating and implementing shared feature files in Cucumber?

I am currently utilizing Cucumber to define some tests for the project I am working on, but as the application grows larger, I find myself in need of a more efficient structure. project | feature_files | | app1.js | | app2.js | | app3.js ...

JavaScript not functional, database being updated through AJAX calls

I have created a game using Phaser, a JavaScript library for games. Now I am looking to implement a score table using JS/PHP. My main focus is on transferring a variable from JS to PHP in order to update the database. I have researched numerous topics and ...

Drop down menu not populating with options

I'm trying to automatically bind the second value in a select drop-down menu that I've created using a list of numbers ranging from 0.01 to 10. getNumbers(); function getNumbers() { $scope.numbersArray = []; for (var j = ...

Having issue updating a MySQL table using an array of objects in JavaScript

Working on a personal project involving React.js for the front-end, Node.js/express for the back-end, and mySQL for the database. The current array is as follows: horaires = [ { jour: 'Lundi', horaire: 'Fermé' }, { jour: 'Mar ...

The setter of the computed property is failing to execute

Currently, I am working with a computed property that represents an object of a specific type defined within my Vuex Store. The goal is to utilize this property in my component using v-model. I have thoroughly set up getters and setters for this property a ...

Looking to automate the clicking of a JavaScript URL upon loading the page

I am currently utilizing the following JavaScript function for a link on the homepage. The requirement is for the link to be automatically clicked upon page load. Link- document.writeln("<a href=\"javascript: live_chat_link(m_sTicketType ...

Magento 2 - The BASE_URL is missing from the product details page

Recently updated my Magento version from 2.2.3 to 2.3.7 and encountered a peculiar issue. On the product details page, I am seeing an error message in the console related to add-home-breadcrumb.js: BASE_URL is not defined. https://i.sstatic.net/Nikep.png ...

Using jQuery to determine if the mouse click is positioned outside a specific div area

Is there a way to modify this code snippet to only execute if a mouse click occurs outside of the #specificDiv element on the webpage? $(document).mousedown(function() { console.log("you clicked somewhere."); }); ...

Generate a D3.js vertical timeline covering the period from January 1, 2015 to December 31, 2015

I am in need of assistance with creating a vertical timeline using D3.js that spans from the beginning of January 2015 to the end of December 2015. My goal is to have two entries, represented by colored circles, at specific dates within the middle of the t ...

Determining the dimensions of knockout-rendered elements

I've implemented knockout to display a list of clickable elements functioning as radio buttons. However, when too many elements are added horizontally, it overflows off the page. Currently, I'm breaking them into multiple rows, but this doesn&apo ...

Retrieve a Play Scala variable in the $scope of an AngularJS application

After trying various methods recommended on StackOverflow, I am still struggling to retrieve a Play Scala variable within my Javascript $scope. The line of initialization in an HTML file is as follows: @(playVariable: String)(implicit request: play.api.mv ...

Nodejs and mysql integrated login system using express

I have created a node.js Express login system with MySQL. Registration and login services are working fine, but the logout functionality is not. Additionally, I want to restrict access to certain pages only to admin users. Here is the file structure: ...

I am having trouble with the TypeScript compiler options not being detected in Visual Studio 2015

After creating an ASP.NET 5 Empty Website project in Visual Studio 2015, I set up a tsconfig.json file with the following settings: { "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false ...

Jquery: Undefined Key/Value Declaration

I'm diving into the world of associative arrays for the first time and trying to access data using keys. While my array is being constructed successfully, I'm struggling to actually retrieve the data. As a result, the console.log statement at the ...

Cart cannot function as a constructor

I'm currently learning express.js and trying to implement a shopping cart/session functionality into my project. Below is the code I have written so far, with a question at the end. Here is my cart.js: // Ensure that the file is required correctly b ...