Error in Nuxt/TypeScript: Unable to retrieve this - TS2339: Property 'XXX' is not found on type

I encountered an issue while working with Nuxt.js and TypeScript. In my project, I rely on dependencies such as axios or nuxt-i18n. As an example, let's focus on Axios. I followed the configuration outlined in the official documentation for nuxt/axios.

nuxt.config.js

export default {
  modules: ['@nuxtjs/axios']
  axios: {},
}

tsconfig.json

{
  "compilerOptions": {
    "types": [
      "@nuxt/types",
      "@nuxtjs/axios"
    ]
  }
}

Now, I aim to utilize $axios within my Vuex store as demonstrated below:

{
  actions: {
    async getIP ({ commit }) {
      const ip = await this.$axios.$get('http://icanhazip.com')
      commit('SET_IP', ip)
    }
  }
}

However, I am currently facing the following error message:

`TS2339: Property '$axios' does not exist on type '{ getIP(state: any, { commit }: { commit: any; }): Promise ; }'.`

Edit: Comment suggestions indicate that using an arrow function might resolve this issue. I attempted the following approach:

export const actions = {
  getIP: async ({commit}) => {
    const ip = await this.$axios.$get('http://icanhazip.com')
    ...
  }
};

Unfortunately, a new error related to "this." arises:

TS7041: The containing arrow function captures the global value of 'this'.

Answer №1

When integrating the axios plugin into your Nuxt application, you need to follow these steps:

import { Plugin } from '@nuxt/types'
import { initializeAxios } from '~/utils/api'

const accessor: Plugin = ({ $axios }) => {
  initializeAxios($axios)
}

export default accessor

Next, create a folder called utils and add a file named api.ts:

import { NuxtAxiosInstance } from '@nuxtjs/axios'

let $axios: NuxtAxiosInstance

export function initializeAxios(axiosInstance: NuxtAxiosInstance) {
  $axios = axiosInstance
}
   
export { $axios }

In your store, you can import the $axios like this:

import { $axios } from '~/utils/api'

...

{
  actions: {
    async getIP({ commit }) {
      const ip = await $axios.$get('http://icanhazip.com')
      commit('SET_IP', ip)
    }
  }
}

For more in-depth instructions, refer to this resource

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

Employing Vue to perform validation on form fields utilizing a method

I am relatively new to Vue, so I appreciate your patience with me. Currently, I am working on a codebase that was created by another developer. The application is simple and consists of a form for data collection. One of the fields in the form is a postcod ...

Ways to link numerous sockets within a single Vue.js project?

import VueSocketIOExt from 'vue-socket.io-extended'; import { io } from 'socket.io-client'; const socketOne = io('http://localhost:3200/'); const socketTwo = io('http://localhost:3100/'); Vue.use(VueSocketIOExt, so ...

Angular2/Typescript: Transforming a Javascript/Typescript Date into a C# DateTime string on the client side

Currently immersed in an Angular2/Typescript project, I am faced with the task of sending a date to a C# backend. Despite my extensive research, all I could uncover through Google searches was information on converting the date on the backend side. My la ...

What are some effective strategies for bypassing CORS requirements in Vue client-side and server-side applications?

I found this amazing MEVN stack tutorial that I've been following: MEVN Stack Tutorial The tutorial is about creating a blog post app, where the client side is built using Vue (referred to as app A) and the backend is built on Express.js providing d ...

Securing the communication with encrypted API request payloads and responses

It concerns me that all data exchanged between the client and server is in raw json format, as it can easily be manipulated by inexperienced hackers trying to tamper with the values. Although it's not possible to hide a secret salt in javascript, I&a ...

Experience the power of VueRouter with the advanced Vue Cypress Component Test Runner

I integrated the Cypress Vue Component Test runner into my existing Vue (Vite) app. However, upon running the test, I encountered an error stating that the $route in my component is undefined. Do you have any insights on what might be missing from my compo ...

Ensuring TypeScript recognizes a class property as definitively initialized when set using a Promise constructor

I have a simple class definition that is giving me an error in TypeScript. class Container { resolveData: (s: string) => void // not definitely initialized error! data: Promise<string> constructor() { this.data = new Promise&l ...

Can you retrieve data or HTML content from the main Vue 3 component?

I have experience using Vue in previous projects but I'm currently facing some challenges on how to pass information/arguments to a root Vue 3 component. My goal is to set up something like this in my HTML: <div class="nav-app" nav=&quo ...

What is the best way to access buffer data in TypeScript for Solana?

Is there a way to retrieve buffer data from TypeScript? I am attempting to use the public key to access all of my token lists, but I am only getting back an empty array of objects. import {Connection, Keypair} from "@solana/web3.js"; const Sola ...

Utilize puppeteer and web-vitals in NextJS to retrieve the web performance metrics of a website

I'm currently working on a basic tool in NextJS that uses puppeteer to fetch web vitals data from a given URL. However, I'm facing an issue where the results are not being printed out. What could be causing this problem? const browser = await pup ...

What could be causing my function to not provide the expected output?

Whenever I try to invoke the function from another part of the code, I encounter an issue where it returns undefined before actually executing the function. The function is stored in a service. login.page.ts: ngOnInit(){ console.log(this.auth.getRole()) ...

Flask Blueprints cannot overwrite the static path

I am attempting to utilize Flask Blueprints for serving a multipage web application. Webapp structure: Landing page html->login->Vuejs SPA Flask structure: app/ client/ dist/ static/ js/ css/ ...

The absence of a `require` definition in Typescript combined with daisyui

Considering using typescript with react and daisyUI (a tailwindCSS component). Just a heads up, I'm currently utilizing vite In my ts.config file, I've specified node as moduleResolution Encountering an error in the tailwind config stating &apo ...

Leveraging ExpressJS and NuxtJS middleware to transmit post data to a webpage

Could someone please assist me in figuring out how to transfer data from a post request to the loaded Nuxt page? I am struggling with sending the data to the page that will be displayed. My goal is to handle the POST request, and then pass that data along ...

Passing arguments inside the source attribute of an image or link tag in Node.js and

As a beginner in NodeJS, I am facing an issue with passing arguments inside links and image sources. In my template.html file, I have included various scripts and elements to create a search form. The issue arises when I try to incorporate values from the ...

What is causing this unique component to be positioned outside of the <tr> tag?

table.vue ... <tbody class="table-body"> <slot></slot> </tbody> ... TableCellRow.vue <template> <td class="table-row-cell" :class="this.class"> <s ...

Extract the sub-element within a parent element using Vue event handling

Objective The main aim is to add a class to the dropdown element .menu-item-dropdown whenever the user clicks on the .menu-item element. Issue Currently, when clicking on the .menu-item element, the returned value from the console.log inside the showMob ...

Selecting keys of an object in Angular 2

Attempting to fetch data from an API using key selection but encountering retrieval issues. File: app/app.component.ts import {Component, OnInit} from 'angular2/core'; import {Http} from 'angular2/http'; import {httpServiceClass} fro ...

What is preventing me from retrieving data from MySQL on a new page using Vue?

My apologies for what may seem like a common inquiry, but I am struggling to achieve a specific functionality. I would like to be able to click on an 'a' tag and have it open a new page displaying an article based on the ID fetched from MySQL Da ...

In Vue using Typescript, how would I go about defining a local data property that utilizes a prop as its initial value?

When passing a prop to a child component in Vue, the documentation states: The parent component updates will refresh all props in the child component with the latest value. Avoid mutating a prop inside a child component as Vue will warn you in the consol ...