The function called Nuxt: n2 is not defined

When using Nuxt 3, I encountered a TypeError that looks like the following:

Uncaught TypeError: n2 is not a function

My issue revolves around a button that triggers the function toggleSelectRow with a @click.prevent directive.

The function in question is as follows:

const toggleSelectRow = (keyword) => {
    if (keywordsSelected.value.find((kw) => kw.uid_kw === keyword.uid_kw) && props.keywords.length > 1) {
        keywordsSelected.value = []
        nuxtApp.$bus.$emit('filter-from-list', '');
    } else {
        keywordsSelected.value = [keyword]
        nuxtApp.$bus.$emit('filter-from-list', keyword.uid_kw);
  }
}

On the receiving end, we have the following code:

$bus.$on('filter-from-list', (newKeyword) => {   filters.keyword = (props.keywords.find((kw) => kw.uid_kw === newKeyword)) ? newKeyword : null   if (!filters.keyword) {
    refreshNuxtData('average-keyword-position');
    return;   }

  fetchKeywordPosition({ keyword: newKeyword }); });

In the provided snippet, nuxtApp is defined earlier with : const nuxtApp = useNuxtApp();

A potential solution was attempted by declaring a function in the receiver component like so:

function filterFromList(newKeyword){
  filters.keyword = (props.keywords.find((kw) => kw.uid_kw === newKeyword)) ? newKeyword : null
  if (!filters.keyword) {
    refreshNuxtData('average-keyword-position');
    return;
  }

  fetchKeywordPosition({ keyword: newKeyword });
}

This function was then called using :

$bus.$on('filter-from-list', filterFromList);
. Despite this attempt, the same error persisted leading me to believe that the issue lies within the sender/receiver mechanism.

Answer №1

One possible issue could be related to scope.

Try manually binding the this in your emitter:

$bus.$on('filter-from-list', filterFromList.bind(this));

Alternatively, Nuxt3 offers a more efficient way to manage global events through Lifecycle Hooks.

You have the option to customize a hook:

// In senders
// Before
nuxtApp.$bus.$emit('filter-from-list', '');
// After
nuxtApp.callHook('filter-from-list', '');

// In receivers
// Before
nuxtApp.$bus.$on('filter-from-list', (newKeyword) => {});
// After
nuxtApp.hook('filter-from-list', (newKeyword) => {});

Lastly, extend the types of #app:

declare module '#app' {
    interface RuntimeNuxtHooks {
        'filter-from-list': (string) => HookResult;
    }
}

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

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

Adjusting the OrbitControl target in a React environment

I attempted to create a model using react-three-fiber and react-drei, but the OrbitControl target setting is causing it to appear too high. import React, { useRef, useState, Suspense, useEffect } from 'react' import { Canvas, useFrame, useLoader, ...

Having trouble with the npm Twitter API functionality?

I'm attempting to execute a simple stream using an example code snippet. Here is the code I am working with: var twit = require('twitter'); var twitter = new twit({ consumer_key: '[KEY]', consumer_secret: &ap ...

JavaScript double-click functionality is not operational on IE9 and IE11 browsers

My JavaScript code has an issue where single-click opens a link in a new tab and double-click opens a lightbox. This works perfectly in all browsers except for IE9 and IE11. In my initial code, both single-click and double-click function correctly. However ...

When using async functions in iterative processes

In my current setup, I am utilizing a for-each loop to handle a list and specifically require element n to be processed only after element n-1 has completed: let elements = ["item1", "item2", "item3"]; elements.forEach(function(element){ someAsyncFun ...

Find the frequency of a specific string within a JSON array

My current task involves working with a stringified array: JSON.stringify(arr) = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","resti ...

What is the best way to merge an array into a single object?

I have an array object structured like this. [ { "name": "name1", "type": "type1", "car": "car1", "speed": 1 }, { "name": &q ...

Tips for deactivating dropdown values based on the selection of another dropdown

There are two dropdown menus known as minimum and maximum, each containing numbers from 1 to 25. If a value is selected from the minimum dropdown (e.g. 4), the maximum dropdown should only allow values that are equal to or greater than the selected value ...

An error is triggered by serializing a TinyBox POST form into an Array

When I implemented the code below, it performed as anticipated: TINY.box.show({url:target, post:$("form[name='currentSearch']").serialize(), width:650, mask:true, close:true, maskid:'boxMask', boxid:'popupBox', openjs:funct ...

Struggling to integrate pdfform.js into a React application

Struggling to integrate the pdfform.js library into my React app. I attempted to use the npm package pdfform, but encountered some difficulties. If anyone has any tips or guidance, it would be greatly appreciated. Check out the pdfform.js library on GitH ...

Vue Component Unit Testing: Resolving "Unexpected Identifier" Error in Jest Setup

Having just started using Jest, I wanted to run a simple unit test to make sure everything was set up correctly. However, I encountered numerous errors during compilation while troubleshooting the issues. When running the test suite, Jest successfully loc ...

Having trouble with Redux's mapStateToProps function?

I'm working on a React component that triggers an AJAX call in the componentWillMount lifecycle method and then stores the fetched data in a Redux store. Here's the code snippet: componentWillMount() { var self = this; var xmlhttp = new XMLH ...

I am facing an issue in my Vue.js/Vite application where importing variables via additionalData becomes unavailable when using @use 'sass:color'

Currently, I am incorporating Vue.js with Vitest along with the sass loader. An issue arises when using @use 'sass:color' in either an inline SCSS file or within a component. It appears to override variables that are defined in css.preprocessorO ...

Attempting to modify the information within the #content division of a webpage through the activation of a linked image within a jquery slideshow

I'm completely stuck on this one, even though I'm relatively new to jquery. My goal is to design a webpage where there is a slideshow of products at the top, and when a user clicks on one of the products, it should update the main #content div w ...

Exploring the Latest PHP Popup Upgrade

Hey everyone, I'm currently facing an issue with updating my MySQL database. I have a popup window that is supposed to update it without any errors, but for some reason, it's not actually updating the database. Can anyone help me figure out what ...

Is there a way to load a URL within a DIV element using AJAX?

These two PHP files are set up to capture a user's input from a form and then display that text. Below you'll find the code for each file: file1.php: <form action="output.php" method="post"> Paste text document: <br> ...

Tips for distinguishing individual rows within a table that includes rowspans?

My Vue application calculates a table with rowspans by using an algorithm based on a configuration file. This allows the application to render columns (and maintain their order) dynamically, depending on the calculated result. For example, see the code sn ...

Error: Unable to locate Buffer2

I encountered the error Uncaught TypeError: Buffer2 is undefined when trying to import jsonwebtoken into my React project. The errors occur with both import jwt from jsonwebtoken and import {decode} from 'jsonwebtoken'. My versions are jsonwebt ...

Including an <a> tag within a JavaScript variable to utilize in an HTML statement

I want to wrap an <a> element around a JavaScript variable containing a string. The desired output should be the 'copyright symbol' followed by the 'companyName' linked as an HTML link and then the current year's date. JavaS ...

Utilizing a Jquery plugin for enhanced form validation with the inclusion of supplementary techniques

I am looking to integrate a jQuery plugin into my form validation process, specifically to ensure that only letters are allowed in the name section. If a user enters special characters or numbers, I want the form to display an error message. Additionally, ...