Using TypeScript along with Nuxt.js and Vuex to access methods from an imported class

Currently, I am in the process of developing a nuxt.js application with typescript and my goal is to segregate the API Calls from the vuex store. However, I've encountered an issue where it seems like I cannot utilize the methods when importing the class. The compiler keeps throwing an error TS1005: ',' expected. each time I attempt to invoke a method.

apiClient.ts

export default class apiClient {
    helloWorld() {
        console.log('Hello World');
    }
}

products.ts:

import ApiClient from '../services/apiClient';

export const actions = {
  ApiClient.helloWorld();
};

tsconfig.json

 "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "baseUrl": ".",
    "paths": {
      "~/*": [
        "./src/*"
      ],
      "@/*": [
        "./src/*"
      ]
    },
    "types": [
      "@types/node",
      "@nuxt/types",
      "@nuxtjs/axios"
    ]
  },

Answer №1

Your code has a few issues that need to be addressed.

Firstly, the way you are defining your actions is incorrect. You should not write your function directly into the actions object. Instead, you need to define a key and then assign your function to that key, like this:

export const actions = {
  helloWorld: ApiClient.helloWorld,
};

It's important to note that you should not include parentheses when assigning your function as it is being assigned, not executed.

Even with this correction, your code will still not compile because you have defined your methods within a class. While there's nothing inherently wrong with this approach, if you choose to use a class, you must instantiate it using the new keyword (or make your class static):

import ApiClient from '../services/apiClient';
const client = new ApiClient();

export const actions = {
  helloWorld: client.helloWorld,
};

In this scenario, it might be simpler to export your functions directly without using a class:

export const helloWorld = () => {
  console.log('Hello World');
};

With this setup, importing becomes easier and you can even omit the key in the exported function name:

import { helloWorld } from '../services/apiClient';

export const actions = {
  helloWorld,
  // or use a different name:
  hello: helloWorld,
};

I hope these suggestions help resolve your issues and clarify why your original code was not functioning correctly.

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

Is it necessary to validate a token with each change of page?

Currently facing a dilemma while working on my react-native app. Uncertain whether I should request the server to validate the token each time the page/screen changes, such as switching from 'feed' to 'profile', or only when actual requ ...

Tips for adding temporary text in filter input of Kendo UI Grid using Angular

I'm currently working with Kendo UI Grid in conjunction with Angular, and I am struggling to find a solution for adding text or a placeholder in filter inputs using Typescript. Within my code, I am utilizing the kendoGridFilterCellTemplate: <kend ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

Is it possible to conceal a table element using [hidden] in Angular 2?

I have a table that includes buttons for adding rows. Table application Question: I am looking to hide the table element and add a show click event on the "Add" button. Here is an example of the HTML code: <div class="col-md-12"> <div class="pa ...

TypeScript React Object.assign method return type

I have a unique custom function that utilizes Object.assign to return a specific result. The documentation mentions that this function returns an array, but surprisingly, it can be destructured both as an array and an object. Check out the code snippet be ...

Utilize the optional chaining feature when accessing properties that may be optional

I recently encountered an issue in my Typescript project where accessing properties or functions of optional properties did not throw any errors. Here is an example: type Example = { bar?: string[] } const foo: Example = {} // Although no error occu ...

What is the best way to organize my NPM package with separate directories for types and functions?

I am currently working on developing a custom NPM package that will serve as a repository for sharing types and functions across my project. Let's name this project wordle. Given the emphasis on types, it is worth noting that I am using TypeScript for ...

Leveraging both function arguments and the 'this' keyword within a single

I have a JavaScript function that utilizes both the `this` keyword and captures arguments: var Watcher = function() { var callbacks = []; var currentValue = null; this.watch = function (callback) { callbacks.push(callback); if (currentValue ...

To utilize this.<module> within a Nuxt plugin, simply access it

How can I access a JS API exposed by a Nuxt module from a client-side plugin? Situation: I am utilizing Buefy/Bulma, which is implemented in nuxt.config.js like this: modules: [ ['nuxt-buefy', {css: false}], ], Buefy provides this.$buefy.&l ...

The upcoming development server will exclusively deliver HTML content without scripts or assets, mirroring the setup of the standard create-next-app template

In an attempt to recreate the problem I am facing, I decided to start by setting up a new Next.js app template folder using the command npx create-next-app (Version 13.1.6==latest, all default options, Node v18.14.0==LTS). However, when I try to run the pr ...

Experience the power of Vue Google Chart - Geochart where the chart refreshes seamlessly with data updates, although the legend seems to disappear

I have integrated vue google charts into my nuxt project. Whenever I select a different date, the data gets updated and the computed method in my geochart component correctly reads the new data. However, the legend or color bar at the bottom does not funct ...

How can I limit the input of string values from a Node Express request query?

export type TodoRequest = { order?: 'asc' | 'desc' | undefined; } export const parseTodoRequest = (requestData: ParsedQs): TodoRequest => { return { order: requestData.order as 'asc' | 'desc' | u ...

"Error TS2339: The property specified does not exist within type definition", located on the input field

When a user clicks a specific button, I need an input field to be focused with its text value selected entirely to allow users to replace the entire value while typing. This is the markup for the input field: <input type="text" id="descriptionField" c ...

Accessing information necessitates two separate subscriptions

I am posting this inquiry in order to enhance my understanding. Below is an excerpt from my service: export class HomeService { private generalstatistics = new ReplaySubject<object>(); constructor( private http: HttpClient ) { this ...

Is there a way to streamline this function call that appears to be redundantly repeating the same actions?

I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can ...

Issues with TypeScript: outFile in tsconfig not functioning as expected

Currently, I am utilizing Atom as my primary development environment for a project involving AngularJs 2 and typescript. To support typescript, I have integrated the atom-typescript plugin into Atom. However, I noticed that Atom is generating separate .js ...

What is the best way to enhance a react-bootstrap component with TypeScript?

Currently, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1d0a0e0c1b420d00001b1c1b1d0e1f2f5e415f415f420d0a1b0e415e5b">[email protected]</a> and delving into the development of a customized Button ...

Capturing the returned value of a mutation in another mutation in Vuex

Having trouble accessing a getter from an action, and receiving the error message: getters.isCardLiked is not a function store/index.js export const getters = { isCardLiked(state, id) { const found = state.likedCards.find(likedCard => liked ...

Jest identifies active handles when executing synchronous scrypt operations in the crypto module of Node.js

During the execution of a unit test using the scryptSync function from the crypto package, I am encountering error messages and warnings that are unfamiliar to me. For instance, here is an example of a unit test I am running in Jest: it('Should match ...

Issue with the manual page refreshing caused by parameters included in the URL

Can you please share your advice on how to handle page reloads (e.g. when a User hits refresh) while using variables in the URL? I have a static site generated with nuxt generate and hosted at http://www.wowrares.com/. The links on the site work fine and ...