I am interested in utilizing $axios in conjunction with Vuex constants for my project

My Dream Becoming Reality

I frequently use this.$axios, so I attempted to store it in a constant, but unfortunately, it did not work as expected. Despite reading the official documentation, I couldn't grasp the reason behind this issue. Could it be due to this not being accessible in the Nuxt.js lifecycle?

Code Snippet

url.js

export const AXIOS_POST = this.$axios.$post

export const POST_API = '/api/v1/'

export const POST_ITEMS_API = '/api/v1/post_items/'

Vuex Implementation

import * as api from './constants/url.js'  // url.js is imported here.

export const state = () => ({
  list: [],
  hidden: false
})

export const mutations = {
  
  add (state, response) {
    state.list.push({
      content: response.content,
      status: response.status
    })
  },


  remove (state, todo) {
    state.list.splice(state.list.indexOf(todo), 1)
  },


  edit (state, { todo, text }) {
    state.list.splice(state.list.indexOf(todo), 1, { text })
  },


  toggle (state, todo) {
    todo.status = !todo.status
  },

  cancel (state, todo) {
    todo.status = false
  },

  // Register action panel flag
  switching (state) {
    state.hidden = !state.hidden
  }
}

export const actions = {

  post ({ commit }, text) {

//The goal is to utilize it at this point

    this.$axios.$post(api.POST_ITEMS_API + 'posts', {
      post_items: {
        content: text,
        status: false
      }
    })
      .then((response) => {
        commit('add', response)
      })
  }
}


Error Encountered

Uncaught TypeError: Cannot read property '$axios' of undefined

Answer №1

If your file is located in a directory named constants, consider using a .env file for configuration. Check out this helpful guide on how to do this in Nuxt:


If you need access to the file in a non-.vue file, you can import it as usual like this:

/constants/url.js

import store from '~/store/index'

export const test = () => {
  // This line will depend on your store setup
  return store.modules['@me'].state.email
}

Note that you have access to getters, dispatch, and similar functionalities here.

To use it in a page or .vue component, follow this example:

<script>
import { test } from '~/constants/url'

export default {
  mounted() {
    console.log('calling the store function', test())
  },
}
</script>

Regarding the lifecycle question, because the url.js file is not within a .vue file but a regular JavaScript one, it does not have knowledge of Vue/Nuxt lifecycles.

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

Experiencing difficulty importing Materialize CSS JS into React

Good day everyone, I've been facing challenges in implementing materialize css into my react-app, specifically with the JavaScript files. After trying various methods, I believe that I have made some progress using the following approach: In my &ap ...

Issues with Angular 2 loading properly on Internet Explorer 11

We are currently running an Asp.net MVC 5 web application integrated with Angular 2. The application functions smoothly on Chrome, Firefox, and Edge browsers, but encounters loading issues on IE 11, displaying the error illustrated in the image below: ht ...

Retrieve the currently displayed page on a bootstrap table

I'm currently utilizing the bootstrap table to showcase my data. One of the features I have added is a column with an edit button for each row. Upon clicking on the edit button, I open a bootstrap modal that displays the data from the corresponding ro ...

Prevent the ability to add options dynamically to a drop-down select list

I have implemented a dynamic data retrieval feature from my database using jQuery's .getJSON function and appended the data to an HTML select drop-down list. The JavaScript code for this functionality is as follows: $.getJSON('url', f ...

Unable to reset the input value to an empty string

I have created a table with a search bar feature that filters the data when the search button is clicked and resets the filter to show unfiltered data when the clear button is clicked. However, the current input value is not clearing from the display even ...

What are some alternatives to using fetch for making API calls in Next.js?

In my NextJS project, I have an express backend where data fetching is required in getServerSideProps. The issue arises when using await fetch('/api/anyApi'), as it does not work with relative paths, and calling to the absolute path await fetch( ...

What is the best way to align a box once another one has been placed?

I have integrated both Bootstrap and Masonry plugins into my website design. The issue I am facing is that the Masonry plugin box goes under the top Bootstrap bar. I tried adding a margin-top: 50, but this resulted in a horizontal scroll bar appearing. To ...

Starting a fresh SSH terminal directly from a web browser

I have an SSH IP address. Is it feasible to launch an SSH terminal through a web browser, similar to clicking on a hyperlink or Google Play store link? For instance: Click Here to Open SSH Terminal Upon clicking this link, the SSH session should open an ...

When I use my loop to generate Google Map markers, the positioning is not accurate and the markers do not appear on the map. However, manually inputting the positions

There seems to be an issue with displaying Google map markers based on objects in the markers array after looping through it. I noticed that when creating a second component and setting the position manually, the marker appears correctly. However, upon ins ...

"Enhance your website with the dynamic duo of Dropzone

Currently, I am utilizing dropzone.js and loading it through ajax. I have assigned my menu ID as "#menu". The uploaded file should display in "#div1". Unfortunately, the callback function is not functioning properly. In an attempt to troubleshoot, I repl ...

The Javascript Ajax loader gif is malfunctioning

I'm currently working on creating an Ajax loader gif using XMLHttpRequest. When I type something in the input field, a list of different words appears. This technique is commonly used in search engines as you type in the search box. However, I am als ...

Invoke a specific URL during an HTML5 upload

So I've got this code that allows for file upload via drag and drop using HTML5 in the browser. $(function(){ var dropbox = $('#dropbox'), message = $('.message', dropbox); dropbox.filedrop({ // Customizing upload settin ...

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...

Creating a Page with Python Selenium for JavaScript Rendering

When using Python Splinter Selenium (Chromedriver) to scrape a webpage, I encountered an issue with parsing a table that was created with JavaScript. Despite attempting to parse it with Beautiful Soup, the table does not appear in the parsed data. I am str ...

When using ngClick with a parameter, the parameter is not being successfully passed

My table resembles a tree structure with two ng-repeats. <table> <tr ng-repeat-start="am in anArray"> <td><button ng-click="TheFunction(am)"></button></td> </tr> <tr ng-repeat-start="em in anotherArray"> < ...

XDomainRequest for cross-domain ajax is throwing an error that is difficult to understand - an empty error message

Here is my AJAX call to a page on a different domain: if ($.browser.msie && window.XDomainRequest) { // Use Microsoft XDR var xdr = new XDomainRequest(); xdr.open("post", "https://different-domain.aspx"); ...

Toggle a MutationObserver using a button to stop and start monitoring for changes

Is there a way to connect a MutationObserver and disconnect it using the same button? I know how to do each separately, but I want to use just one button. How can I achieve this? Apologies for my poor English. var target = document.getElementsByClassNa ...

Utilize jQuery to target elements containing more than one class

Suppose an element has several classes as shown below: class="btn btn-primary add-movie-button is-on" Is it possible to select this element using only one class name with jQuery, for example: $(".add-movie-button") Can the method .hasClass("is-on") be ...

What improvements can I make to enhance my method?

I have a block of code that I'm looking to clean up and streamline for better efficiency. My main goal is to remove the multiple return statements within the method. Any suggestions on how I might refactor this code? Are there any design patterns th ...

Showing text above bars in MUI X BarChart

I am currently utilizing the <BarChart> component from @mui/x-charts (version "^6.19.1") and I am looking to enhance readability by displaying the data values on top of each bar. Current Output: view image description here Desired Outc ...