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

Updates to props values are not being reflected in the React js application running on the webpack

I keep facing an issue where I have to restart the webpack server every time I try to pass or update props values from parent to child components. It's frustrating that the props values are not updating even after saving the file. Take a look at my p ...

Issues with AngularJS dirty validation for radio buttons not being resolved

I have encountered an issue with my form fields. The validation for the email field is working correctly, but the radio button field is not displaying any errors when it should. I am using angular-1.0.8.min.js and I cannot figure out why this is happenin ...

Creating and fetching CSV files using PHP and AJAX

I have successfully created a PHP script that generates a CSV file for automatic download by the browser. The code below shows a working version with sample data for different car models. <?php $cars = array( array("Volvo",22,18), array("BMW",15,1 ...

The inability to read property 0 of undefined persists despite implementing conditional rendering

I'm struggling to understand what mistake I'm making in the current situation: There's an array named arrayOfChildren that gets initialized like this: const [arrayOfChildren, setArrayOfChildren] = React.useState([]) With a handler function ...

Utilize Express Node to display API information on HTML pages using Handlebars template

I'm seeking assistance in rendering data from an API to HTML using handlebars. I'm a bit puzzled on how to properly showcase the data on the webpage. Here's what I have so far: ROUTES FOLDER/FILE: const express = require('express&ap ...

Error Timeout Encountered by Langchain UnstructuredDirectoryLoader

I am facing an issue while trying to load a complex PDF file with tables and figures, spanning approximately 600 pages. When utilizing the fast option in Langchain-JS with NextJS Unstructured API, it partially works but misses out on some crucial data. On ...

Having trouble with a dropdown menu that allows for multi-select options?

var expanded = false; function showCheckboxes() { var checkboxes = document.getElementById("checkboxes"); if (!expanded) { checkboxes.style.display = "block"; expanded = true; } else { checkboxes.style.display = "none"; expanded = fa ...

Ionic 3 Storage Timing Explained

I have a scenario where I am trying to load JSON data from storage and display it on the HTML template of my page. However, when I try to do this, I encounter errors suggesting that the information is not yet available upon entering the page. I'm sta ...

What is the best way to streamline the if statement in JavaScript?

Here is the given code snippet: public noArtistBeingEdited(): boolean { if (this.isFirstNameBeingEdited()) { return false; } if (this.isLastNameBeingEditable()) { return false; } return true; } What are some ways to ma ...

I just obtained the height measurement of a dynamic table - now I must transfer this height value to a different element

Recently, I encountered a situation where I needed to get the height of a dynamic table using code like this: var table = document.getElementById("test"); document.write(table.offsetHeight); However, the challenge arose when I realized that I also needed ...

Create a script that will split a single block of text into separate sections based on predefined conditions

I have developed a script using Tampermonkey which modifies a value on a specific webpage. On the webpage, there is an input box with the value "FPPUTHP1100000". This value is a material code with the following structure: F represents FRESH PPUTHP repr ...

What is the proper way to implement parameters and dependency injection within a service?

My objective is to achieve the following: (function(){angular.module('app').factory("loadDataForStep",ls); ls.$inject = ['$scope','stepIndex'] function ls ($scope, stepIndex) { if ($routeParams ...

Issue with Javascript Promise causing failure to populate list with objects

app.get('/zones/:id/experiences', function(req,res) { var zone_key = req.params.id; var recent = []; var ref = firebase.database().ref('participants/'+zone_key+'/experiences'); ref.on("value", function(snapshot) { ...

Can you suggest a method using Lodash to remove specific rows from an array based on the value of a certain field within the array?

Currently, I am utilizing the following function: remove: function (arr, property, num) { for (var i in arr) { if (arr[i][property] == num) arr.splice(i, 1); } }, Although this functi ...

Experimenting with a function that initiates the downloading of a file using jest

I'm currently trying to test a function using the JEST library (I also have enzyme in my project), but I've hit a wall. To summarize, this function is used to export data that has been prepared beforehand. I manipulate some data and then pass it ...

Angular ng-repeat not populating the list properly, causing a collapse not to display

Currently, I am working on developing an app using Angular.js and Bootstrap UI, but I have run into a problem with a collapse navigation feature. The issue I am facing is that I have an ng-repeat that should be functioning properly. However, when I click ...

Having issues with Cypress testing of Material-UI datepicker on Github actions

Encountering an unusual issue while running Cypress tests in a GitHub action environment. The MUI datepicker is stuck in readonly mode, preventing any input of dates (works fine in other setups). Error displayed by Cypress CypressError: Timed out retryin ...

React Leaflet causing a frequent map refresh due to context value updates

When I use map.on('moveend') to update the list of markers displayed in another component, I encounter a refreshing issue. The context in my project contains two arrays - one filtered array and one array with the markers. When I try to update the ...

Guide to displaying a pop-up modal containing text and an image when clicking on a thumbnail image

Recently delving into Bootstrap 3, I created a thumbnail grid showcasing images related to various projects. My goal is to have a modal window pop up when clicking on an image. Within the modal, I want to display the selected image alongside some descrip ...

Implement modals using a for loop in Vue

I am facing an issue while trying to create modals for cards within loops. I attempted using v-bind:id="masa._id" and v-bind:data-target="'#'+masa._id", but the modal is not working. Can someone guide me on how to implement modals in loops? Belo ...