Retrieve vuex state in a distinct axios template js file

I have encountered an issue with my Vue project. I am using Vuex to manage the state and making axios requests. To handle the axios requests, I created a separate file with a predefined header setup like this:

import axios from 'axios'
import store from '../store/index'

export default axios.create({
  baseURL: 'https://example.com/',
  timeout: 1000,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${store.getters.getToken}`
  }
})

The problem I am facing is that the store is undefined in this case. I have tried importing the store into the /src/axios/request.js file using

import { store } from '../store/index'
. My Vuex store setup looks like this:

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'

Vue.use(Vuex)

export default new Vuex.Store({
  namespaced: true,
  modules: {
    user
  },
  state: {
    url: 'https://example.com/',
    token: '',
  },
  getters: {
    getToken: state => state.token
  },
})

If anyone has a repository showcasing a project structure with Vuex modules and axios requests set up in a separate file with a predefined template, I would appreciate it if you could share it. I'm looking for guidance on how to better organize my project. Thank you for any assistance provided.

Answer №1

Implement a factory function for generating the axios instance.

// request.js
import axios from 'axios'

const createAxiosInstance = (token) => {
  return axios.create({
    baseURL: 'https://k-3soft.com/',
    timeout: 1000,
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    }
  }
})

export default createAxiosInstance

Utilize the created axios instance in a module:

// user.js
import createAxiosInstance from '../request.js'


const userModule = {
  // ...
  actions: {
    async performSomeAction ({ state, commit, rootState }) {
      const axios = createAxiosInstance(rootState.token)

      const response = await axios.post('/some/api/endpoint')
        .then(response => response)
        .catch(error => {
           // handle error
        })

      commit('SOME_MUTATION', response.data)
    }
  }
}

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

What is the best way to update the text on buttons once they've been clicked for a variety of buttons

I'm encountering an issue with multiple buttons where clicking on any button causes the text to change on the first button, rather than the one I actually clicked on. All buttons have the same id, and using different ids for each button seems impracti ...

The loading animation does not appear in the NextJS 14 - loading.tsx component while a GET request is being processed

Component with 500 photos displayed on my page: 'use client'; import { useEffect, useState } from 'react'; import { wait } from '@/components/loaders/skeletons'; export default function Postings() { const [photos, setPhotos ...

Issues with method invocation in jQuery's .ajax requestI am having

After reading this Stack Overflow post, I now understand how to retrieve a return value from an AJAX call: function GetIsDataReady(input) { $.ajax({ url: "http://www.blah.com/services/TestsService.svc/IsDataReady", ...

Steps to retrieve the latest value of a specific cell within the Material UI Data Grid

After updating the cell within the data grid, I encountered an issue where I could retrieve the ID and field using the prop selectedCellParams, but retrieving the modified value was proving to be challenging. In order to successfully execute the PUT reque ...

Disable reloading when submitting and reset input fields after submission

I am working on developing a website where users can post things and comments without the need to refresh the page. I have encountered some issues while implementing this feature and need some assistance with it. My goal is to allow users to submit comment ...

Tips for fixing an error encountered when running a react native project for the first time

I am encountering some errors while attempting to run this project for the first time and I am unable to resolve them. Below is the content of the package.json file: { "scripts": { "start": "expo start", "andro ...

When using `element.addEventListener`, event.target will be the target

When working on a solution, I initially bound event listeners to multiple targets within the same container. I am curious to know if anyone has noticed considerable performance improvements by using just one event listener and leveraging the target of the ...

Is there a way to implement absolute imports in both Storybook and Next.js?

Within my .storybook/main.js file, I've included the following webpack configuration: webpackFinal: async (config) => { config.resolve.modules = [ ...(config.resolve.modules || []), path.resolve(__dirname), ]; return ...

"Using Node.js Express 4.4 to efficiently upload files and store them in a dynamically

Looking for recommendations on the most efficient method to upload a file in node.js using express 4.4.1 and save it to a dynamically created directory? For example, like this: /uploads/john/image.png, uploads/mike/2.png ...

divide an array into two separate arrays depending on whether the index position is odd or even

Here is an example array: Arr1 = [1,1,2,2,3,8,4,6]. I'm trying to divide this array into two new arrays based on the odd or even position of elements. Can anyone provide a solution? New Array 1 (odd positions): [1,2,3,4] New Array 2 (even positions) ...

The Foolish Mistake: Undetermined Dollar Sign

Can someone please help me with this issue? I've searched everywhere but I can't seem to fix the "Uncaught ReferenceError: $ is not defined" error. I have rearranged my script, tried putting it at the bottom, but nothing seems to work. Any sugges ...

How to retrieve the value instead of the key/ID in a Laravel controller?

I am extracting data from the database and displaying it on the invoice view page using the json_encode($items); function. When I try to insert the 'price' field into the database, only the id/key is being stored instead of the actual value. Any ...

ERROR_UNSUPPORTED_ESM_URL_SCHEME - issue with next-sitemap plugin

I have a project utilizing next-sitemap with Node.js version v14.11.0. next-sitemap.config.js module.exports = { siteUrl: 'https://*****.com', generateRobotsTxt: true, robotsTxtOptions: { additionalSitemaps: [ 'htt ...

The Vue background container fails to display the image

I'm having trouble setting an image as the background for a div element. Despite my numerous attempts, I haven't been able to make it work. No results are displayed and there are no error messages to indicate what went wrong. I recently stumble ...

Unable to capture screenshot of hovered element using Cypress

Having an issue with taking a screenshot of an element with a hover effect. The screenshots always come out without the hover effect applied. tableListMaps.lineWithText('Hello world', 'myLine'); cy.get('@myLine').realH ...

Error in VueJS: Computed property not updating as expected due to lacking a setter function (which is

I've created a Wrapper component that wraps a third-party component. Here's how it looks: <template> <custom-element v-model="computedProperty" > </custom-element> </template> <script> export default { ...

Tips for avoiding the push method from replacing my items within an array?

Currently, I am diving into Typescript and VueJS, where I encountered an issue with pushing elements to my array. It seems to constantly override the 'name' property. Let me share the code snippet causing this problem: const itemsSelectedOptions ...

Having difficulty adding multiple items to the state array

I am currently working on a parent component that iterates over an array and passes props to a child component. In the child component (shown below), I have checkboxes with Font Awesome icons for users to mark their selections. When a user checks a box, I ...

Is there a way for me to determine if a domain has been registered by the client?

I'm interested in creating a Web app that allows users to enter a domain name and then uses JavaScript to check its availability. I'm wondering if there's a method to do this without relying on my own hosting server. Is it possible to send a ...

Reply after performing several asynchronous queries using mongoose and express

When trying to create a list of products to send to a client, I am encountering an issue where res.send executes before the loop has completed. I have tried using async/await but it doesn't seem to work. Any suggestions on how to resolve this? Below ...