What is the recommended way to retrieve the Nuxt `$config` within Vuex state? Can it only be accessed through store action methods?

After using the dotenv library for my .env file, I had to change the runtimeConfig in order to secure my project's secret key.

In my most recent project, I utilized nuxt version "^2.14" in SPA mode, so I only utilized "publicRuntimeConfig" in my nuxt.config.ts file like this:

.env

Test_BASE_URL:'https://test.org'

nuxt.config.ts

export default {
   publicRuntimeConfig:{baseURL: process.env.Test_BASE_URL||''}
}

I was able to access the env variable in a vue file like this:

sample.vue

<script>
export default {
 mounted(){
  console.log(this.$config.baseURL)
 }
}
</script>

However, I encountered difficulty accessing "$config" in the store's state. I attempted to do it but it always returned "undefined."

index.ts

export const state = (context) => ({
  url:context.$config
})

Upon referring to some solutions from others and changing the state value through actions, especially since I was using SPA, I created a method like 'nuxtServerInit' as plugins.

plugins/clientInit.ts

import {Context} from "@nuxt/types";

export default function (context:Context) {
 context.store.dispatch('initEnvURL', context.$config)
}

index.ts

interface State {
 testURL: string
}
const state = () => ({
 testURL:''
})
const mutations = {
 setTestURl(state:State, config:any) {
  state.testURL = config.baseURL
}
const actions = {
 initEnvURL({commit}, $config) {
 commit('setTestURl', $config)
}
}
export default {state, mutations, actions}

I did manage to successfully change the state value through the above actions methods, but I am still unsure why "context" cannot directly use store/state objects. Does anyone have insight on how to utilize $config in store/state? Or is the only way to use $config through actions method as shown above?

Answer №1

One reason for this behavior in Vuex is that only actions are able to access the app context. State, mutations, and getters are intentionally designed not to have this capability.

It's important to ensure that your initial state does not rely on any runtime-specific values, as it should be contextless.

Mutations are intended to be stateless, simply taking a parameter to update the state. Any context-dependent data should be passed from the calling code.

Getters are meant for reactive state transformations and should not depend on context properties, as this could interfere with the Vuex module's state.


To address this issue, you should initialize your store within the nuxtServerInit action (or from a plugin for SPA apps) like so:

nuxtServerInit({ store, config } ) {
   store.commit('UPDATE_BASE_URL', config.baseUrl)
}

Answer №2

Even with @nuxt/types, the type system doesn't recognize it.

To access it, you can refer to either store/index.ts or store/module.ts:

import { ActionTree, MutationTree } from 'vuex'

const actions: ActionTree<ModuleState, RootState> = {
   async yourActionName({ commit }, payload): Promise<void> {
      try {
         let url = this.app.$config.baseURL + "/path"; // <- accessing config here.

         const res = await this.$axios.get<number>(url);

         commit("mutateState", res.data);

         return;
      } catch (error) {
         // Error handling
      }
   },
};

Below is my nuxt.config.js setup:

export default {
...
   publicRuntimeConfig: {
     baseURL: process.env.BASE_URL || 'http://localhost:5000/api',
   }
...
};

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

Exporting functions using reactjs and babel

I'm currently working on a project that involves using reactjs, transpiled by babel with es2015 and react transforms configured in my .babelrc file. In the initial stages of refactoring, I realized that many of the classes should actually be functions ...

perform one task following the completion of another

Can I run the second function after the first one without using a timeout event in this JavaScript code: if (direction !== "leftnav") { // DO THINGS }; setTimeout(function () { //DO OTHER THINGS AFTER THE FIRST THING }, 1000); Your input is greatly app ...

Update the text on the button after it has been clicked

Hello fellow developers, I have this issue with my code that copies the URL to the Clipboard. The problem is that after it's clicked, it stays on "copied". I want it to change back to its original state. I know this question has been asked many times ...

From integrating Vue 2 TSX to React TSX: ensuring seamless cooperation

Currently, my app is built with Vue 2 using vue-tsx-support, vue-class-component, and vue-property-decorator. All of my Vue 2 components are already TSX classes. I am interested in gradually transitioning to React. I experimented with https://github.com/ ...

The value of Component.name is not consistent during the BUILD process in NextJS

I have multiple pages with different layouts. To switch between layouts, I am currently using the Component.name in _app.js. While this approach works during development, after building and starting the project with npm start, it seems like the Component.n ...

What is the best way to implement a comprehensive switch case in Typescript using string enums that are referencing other string enums?

I am faced with a challenge where I have a subset of values from one enum that I need to switch case across in TypeScript. Here's an example to illustrate my dilemma: const enum Fruit { APPLE = 'Apple', BANANA = 'Banana', ...

Having issues with the input event not triggering when the value is modified using jQuery's val() or JavaScript

When a value of an input field is changed programmatically, the expected input and change events do not trigger. Here's an example scenario: var $input = $('#myinput'); $input.on('input', function() { // Perform this action w ...

React: Using Chart.js to visualize negative values with a different color in the area

I am implementing a line chart using Chart.js and react-chartjs-2 to display positive and negative values. For positive values, I want the filled area to be green, and for negative values, I want it to be red. Check out the code here import React from &qu ...

Another option instead of using useCallback

Forgive me if this is a novice inquiry, but I am still learning JavaScript and React. I recently discovered the necessity of utilizing useCallback to wrap callback functions in order to prevent them from being recreated constantly when used within a fun ...

Tips on displaying the entire text when hovering over it

I'm facing an issue with a select element that retrieves options from an API. The problem is that some options are too large for the text box and get cut off, making them hard to read for users. <div class="form-group my-4"> <lab ...

Is there a way to trigger a function for both a left and middle click at the same time?

Check out this code snippet: $('a').on('click', function(){ myfunc($(this)); }); function myfunc(el){ console.log('Either left or middle click clicked on the link'); } a{ cursor: pointer; } <script src="https://aj ...

Track and log async routes for undefined values once await is complete

Currently facing challenges with multiple queries and synchronous code while writing an Express endpoint in TypeScript to update a user's password in the database. The issue I am encountering is that when attempting to await the return of a function, ...

ReactJS - Common Mistakes in Writing Code

I'm a beginner in Javascript and struggling to resolve this issue. When I declare my 'params' variable with var, I encounter an error stating "[js] Unexpected token. A constructor, method, accessor, or property was expected." You can take a ...

Encountering a problem with Node.js because of a SyntaxError: Receiving an

Recently, I decided to dive into learning node.js and attempted something very basic: displaying a "Hello World" message from the server. The code snippet I used (taken directly from a book) is as follows: var http = require("http"); http.createServer(fu ...

Retrieve information from an API and populate a MDBootstrap datatable using Vue.js and Axios

I am looking to populate a mdbootstrap datatable with data from my API. Is there a way for me to create a method that can call the getPosts() API and then write the results into the rows[] array? <template> <mdb-datatable :data="dat ...

`The Streaming module within React Native`

I am facing an issue in my React Native project where I want to use a node library that depends on stream (require('stream')). The problem arises with the error stream could not be found within the project because stream is a nodejs package not ...

Tips for creating a secure authentication system in an AngularJS application!

As a novice in the world of angularjs... After going through the documentation and completing a tutorial, I decided to experiment on my own which has helped me grasp things better. Now, I'm looking into creating a secure authentication system. The ...

In a peculiar occurrence, the behavior of array.splice is exhibiting unusual characteristics within an

Be sure to take a look at this plunkr for reference: http://plnkr.co/edit/FQ7m6HPGRrJ80bYpH8JB?p=preview I'm encountering an issue where, after adding an element and then deleting it from the array using the splice method, everything becomes disorg ...

Enhance Your Charts: Learn how to dynamically adjust zoom levels between two timestamps with just a simple form submission

I have a Zingchart Area Graph that displays events on a timeline with time on the X-Axis. I want to be able to automatically zoom into a specific timeframe on the graph based on user input from a form. For example, if a user selects a start time of 8 AM an ...

Exploring Variations in Color with React-three-fiber

When using both meshBasicMaterial and meshStandardMaterial in a React Three Fiber component to render a box with an image texture, the texture appears different from the original image. Despite trying to set colorManagement={false} in the canvas component, ...