Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show the updated queries in the URL.

I'm aware that NuxtJS plugins run once the page is loaded, but is there any way to have the query updated each time these functions are used?

export default (ctx: NuxtConfig, inject: Inject) => {
  const { app, query } = ctx;

  const global = {
    changePage (page: number) {
      console.log(query);
      
      app.router.push({
        query: { ...query, page }
      })
    },

    changeLimit(limit: number) {
      console.log(query);

      app.router.push({
        query: { ...query, limit }
      })
    },
  }

  inject('global', global)
  ctx.$global = global
}

Answer №1

To improve your plugin, consider removing the line ctx.$global = global from the last part of it.

The Nuxt framework offers the convenient inject method to ensure that your global object is easily accessible when required. Therefore, there's no necessity for you to overwrite the ctx.$global property.

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

Different ways to reference a variable in Typescript without relying on the keyword "this" throughout the codebase

Can we eliminate the need to write "this" repeatedly, and find a way to write heroes, myHero, lastone without using "this"? Similar to how it is done in common JavaScript. https://i.stack.imgur.com/TZ4sM.png ...

Using SCSS based on the browser language in Angular: A Step-by-Step Guide

Is there a way to implement SCSS that is dependent on the user's browser language? When I checked, I found the browser language specified in <html lang = "de"> and in the CSS code as html[Attributes Style] {-webkit-locale: "en&quo ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

The error message "SyntaxError: Cannot use import statement outside a module" popped up while working with discord.js, typescript, heroku

// Necessary imports for running the discord bot smoothly import DiscordJS, { TextChannel, Intents, Message, Channel, NewsChannel, ThreadChannel, DiscordAPIError } from 'discord.js' type guildTextBasedChannel = TextChannel | NewsChannel | ThreadC ...

Having trouble with the jQuery load function not functioning properly

I have encountered an issue with this code snippet while running it on XAMPP. The alert function is working fine, but the HTML content fails to load. I have included links to jQuery 3.2.1 for reference. index.html $(document).ready(function(){ $("#b ...

prevent unnecessary duplicate database queries for generating metadata in the upcoming 13 or 14 instances

In the latest updates, version 13 and 14 of Next introduced the usage of the generateMetadata function as the preferred method to define all page metadata. However, a drawback of this approach is that because of the separation of logic, fetching data base ...

Typescript is missing Zod and tRPC types throughout all projects in the monorepo, leading to the use of 'any'

Recently, I've found myself stuck in a puzzling predicament. For the last couple of weeks, I've been trying to troubleshoot why the types are getting lost within my projects housed in a monorepo. Even though my backend exposes the necessary types ...

A static method written in Typescript within an abstract class for generating a new instance of the class itself

Imagine I have abstract class Foo { } class Bar1 extends Foo { constructor(someVar) { ... } } class Bar2 extends Foo { constructor(someVar) { ... } } I want to create a static method that generates an instance of the final class (all construct ...

Encountering difficulties in accessing state while utilizing async callback functions in React.js

After finding this function on Stack Overflow, I decided to use it in order to update a database and profile information immediately after a user signs up. The function is working as expected, but I am encountering an issue where I can no longer access the ...

I'm intrigued: what type of syntax is Facebook's polling service utilizing in the callback?

While monitoring the Network Monitor on Chrome's developer tool, I observed how Facebook updates content on their news feed. All AJAX responses start with the following: for (;;);{"__ar":1,"payload":[]} I'm curious about what the for(;;); piec ...

Encountering 'Illegal Invocation' error while running a basic script

Exploring the Speech Recognition API has been on my to-do list, so I decided to create a simple page that initiates recognition when clicking on the body element. Here is a snippet from my scripts.js file: var recognition = new window.webkitSpeechRecognit ...

The cross-domain AJAX request fails to receive a response

I am currently working on validating PAN card details. I am utilizing an AJAX call to verify the PAN card entered by the user, sending the PAN number to this URL: . The data is being sent to the following URL using AJAX call: function callbackFnc(data) { ...

Enhance the "text" attribute of IXMLDOMElement to enable functionality in Chrome

The web application I am currently working on was developed approximately 10 years ago and is only compatible with Internet Explorer. My goal is to make it functional in Chrome as well. I am facing a challenge regarding the "text" property of IXMLDOMEleme ...

Top method for refreshing component data from a different component in Nuxt

Being new to Nuxt and Vue, I'm unsure about the best approach for this particular scenario. I am looking to dynamically change the text (such as "Home", "Settings", "Favorites" etc.) within my Header.vue component (which is always fixed at the top of ...

Tips for implementing Material-UI components in a .ts file

I am currently working on some .ts files for mocks, and I have a question about inserting MUI elements such as the Facebook icon. export const links: Link[] = [ { url: "https://uk-ua.facebook.com/", **icon: <Facebook fontSize ...

Issue with converting string to Date object using Safari browser

I need to generate a JavaScript date object from a specific string format. String format: yyyy,mm,dd Here is my code snippet: var oDate = new Date('2013,10,07'); console.log(oDate); While Chrome, IE, and FF display the correct date, Safari s ...

automatically loading data using jquery

I am currently utilizing a windows service along with an html+j query page to interact with a web service. Whenever a Document is scanned on our device, I aim to display: name, country, and Passport number on our webpage. Although I have successfully a ...

Retrieve JSON object by matching another JSON property

I am working with an array of id's and their respective contents in a JSON response. My goal is to retrieve the content based on the received id. For instance, if the ID is 1 (returned from the JSON), I aim to access the JSON data using "data.id" (wh ...

Issue with AngularJS controller method not functioning properly when assigned to a Div

I am facing an issue with a login form and its controller. The login function is not triggering upon submitting the form for some reason. Here is the code snippet for the form within the larger view file: <div class="login-wrap" ng-controller="LoginCt ...

Unable to activate IndexedDb persistence with Firebase v9 in a Next.js PWA

I'm having trouble enabling IndexedDb persistence in Firebase v9 for a Next.js PWA. These errors keep popping up: index.js // main Firebase file import { initializeApp } from 'firebase/app' import { getAuth } from 'firebase/auth' ...