Loading data into the Nuxt store upon application launch

Currently, I'm working on an app using Nuxt where I preload some data at nuxtServerInit and store it successfully. However, as I have multiple projects with similar initial-preload requirements, I thought of creating a reusable module for this logic. The idea was to easily add the module to the nuxt.config.js in all my other projects to automatically populate the store. But, during the module creation process, I realized that there seems to be no way to access the store at that point. Am I correct in this assumption?

I attempted to use

nuxt.hook('ready', (nuxt) => {...}
, but unfortunately, the nuxt-parameter provided in the callback does not include a reference to the store.

As someone new to Nuxt, I may be missing something crucial or handling my preload issue incorrectly. Is there a better approach to solving this dilemma?

Shown below is my attempt at creating the module named modules/mymodule.ts:

const mymodule: Module<Options> = function (moduleOptions: Options) {
  const { nuxt } = this

  nuxt.hook('ready', async (__nuxt: any) => {
    // __nuxt ... no store reference :(
  })
}
export default mymodule

Answer №1

Insight on Vue 2:

In a similar situation, I found the solution by locating the store within the moduleOptions.

To access the store in my case, I implemented a plugin.

// nuxt.config.js

buildModules: [
    '@unique_namespace/node_modules_path',
]

// custom-plugin.js

// Ensure that when initializing module in nuxt.config, 
// only the plugin is relocated (not dependencies) to prevent resolution errors.
// REFERENCE: https://github.com/nuxt/nuxt.js/issues/9876
import CustomStore from '@unique_namespace/node_modules_path/store'

export default function ({ store }) {
  store.registerModule('custom-store', CustomStore())
}

// specific-module.js


module.exports = async function (moduleOptions) {
  const options = {
    ...this.options['my-custom-plugin'],
    ...moduleOptions,
  }

  this.addPlugin({
    src: resolve(__dirname, 'custom-plugin.js'),
    fileName: 'my-custom-plugin.js',
    options,
  })
}

module.exports.meta = require('../package.json')

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

Adjust the specific data type to match its relevant category

Is there a method to alter literal types in TypeScript, for instance. type T1 = ""; type T2 = 1 I am interested in obtaining string for T1 and number for T2. Regarding collections, I am unsure, but I assume it would involve applying it to the generic typ ...

I encountered an error stating "Buffer is not defined" originating from the Deode/Encode Stream Bundle.js script, not from my own code

I've encountered a major issue while attempting to update my npm project to webpack 5, and now I'm left with just one persistent error: bundle.js:1088566 Uncaught ReferenceError: Buffer is not defined at bundle.js:1044980:24 ...

I am looking for an Angular Observable that only returns a single value without any initial value

Is there a way to create an Observable-like object that calls a webservice only once and shares the result with all subscribers, whether they subscribe before or after the call? Using a Subject would provide the result to subscribers who subscribed before ...

The React Typescript error message: "Type '' is not compatible with type 'null'"

I have started working on a simple todo app using React and TypeScript. As I am creating a context, I encountered an error regarding the value of the content provider. <TodoContext.Provider value={contextValue}>{children}</TodoContext.Provider> ...

Testing Angular2 / TypeScript HTTPService without Mocking: A Guide

import {Injectable} from '@angular/core'; import {Http} from '@angular/http'; @Injectable() export class HttpService { result: any; constructor(private http:Http) { } public postRequest(){ return this.http.get('h ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

Solving the 'never' type issue in Vue3 and TypeScript for an empty array reference

I am currently in the process of migrating a component from an old Vue project that relies solely on JavaScript to a TypeScript/Vue project, and I have encountered some obstacles along the way. <script lang="ts"> import { computed, ref } fr ...

constrain a data structure to exclusively contain elements of a particular data type

interface Person { id:number, name:string } const someFunction(people: ???) => {...} Query: Can the people parameter be typeguarded to only allow an object with all properties matching a Person interface, similar to the following structure: pe ...

Creating a dedicated class or module specifically designed for handling import and export tasks is a highly efficient approach towards stream

Exploring different ways to import multiple classes into a single class file: import myClass1 'pathto1'; import myClass2 'pathto2'; import myClassn 'pathton'; Seeking a simpler method using one file (class export) with al ...

The function in Angular 5/Typescript disappears when attempting to call it from within another function

After importing D3 into my component, I encounter an issue when trying to assign a layout to the D3.layout property. Strangely, although the layout property is present in the console output of my D3 object, it seems to be unknown when I attempt to call i ...

Choose a row by selecting the checkbox in the Kendo UI grid using TypeScript

I'm just starting out with Kendo UI and Angular 2, and I'm currently working on integrating Kendo UI with Angular 2. Specifically, I have a Grid Module set up with checkboxes in each row. My goal is to extract the row ID or any other field value ...

Issue: The element '[object Object]' is of type 'object', which is not supported by NgFor. NgFor only works with Iterables like Arrays. - Problem encountered in an Ionic Project

I'm currently working on retrieving my user's username from Firebase Firestore Database using Ionic and AngularFire. I have implemented the valueChanges() method to obtain the observable and am trying to process it using an async pipe. However, u ...

Encountering challenges with reusing modules in Angular2

I am currently working on an angular2 website with a root module and a sub level module. However, I have noticed that whatever modules I include in the root module must also be re-included in the sub level module, making them not truly reusable. This is w ...

Angular Dialog Component: Passing and Populating an Array with Mat-Dialog

Here's the situation: I will enter a value in the QTY text field. A Mat dialog will appear, showing how many quantities I have entered. My question is, how can I iterate an object or data in the afterclosed function and populate it to the setItem? Cur ...

Learn how to set up a class using TypeScript decorators

Is there a way to automatically initialize a class when a specific decorator is present above the class? For example: @apiController export class usersControllers extends lib.baseClasses.apiControllerBase().apiController { @lib.decorators.routesRegist ...

Acquired this as empty

I encountered a strange error message saying "this is null" and I can't figure out what the issue is. Here is my demo on Stackblitz.com with an example code for your reference. Component ngOnInit() { this.getCurrentLocation(); } getCurrentL ...

Is there a way to customize the default MuiCheckbox icon in theme.ts?

How can I customize the icon default prop for Mui checkbox? I followed the instructions provided here and used a snippet from the documentation: const BpIcon = styled('span')(({ theme }) => ({ borderRadius: 3, width: 16, height: 16, .. ...

implementing firestore onsnapshotListner feature with pagination

I have a web application that needs real-time updates on a large collection of documents. However, due to the size of the collection, retrieving data without applying a limit is not feasible and inefficient. Therefore, it is crucial to implement a query li ...

Setting up the TypeScript compiler locally in the package.json file

UPDATE #1: It appears that I have managed to come up with a functional configuration, but I am open to any suggestions for improvement. Feel free to check out the answer here: THE ORIGINAL INQUIRY: I am in the process of setting up my environment so that ...

In case of an API error with the Nuxt fetch method, ensure that the entire site responds with a 404

Is it possible to configure a Nuxt website to respond with a 404 error when the API raises a 404 error? The API call is made on the client side using the fetch method: Check out this demo here: codesandbox demo Code Snippets index.vue <template> ...