The function called within the XState machine cannot be invoked from within the class, yet it functions properly when defined as a

Is there a reason why I can't reference a method declared within the same class as XState service? It seems to work fine when the method is moved outside of the class.

export class LoaderMachine {
    service = interpret(createMachine<LoaderContext, LoaderEvent, LoaderState>(
        {
        .....
        }, {
            actions: {
                fetch() {
                    this.fetchDataInsideClass(); // not callable
                    fetchData(); // global declaration works
                },
                restart() {
                    console.log('Recovering from error')
                    service.send('RESTART');
                },
                finished(context, event) {
                    console.log('Done');
                }
            }
        }));

    async fetchDataInsideClass() {
        try {
            console.log('Started');
            service.send('SUCCESS');
        } catch (err) {
            console.error(`Failed with ${err}`);
            service.send('ERROR');
        }
    }
}

async function fetchData() {
    try {
        console.log('Started');
        service.send('SUCCESS');
    } catch (err) {
        console.error(`Failed with ${err}`);
        service.send('ERROR');
        }
    }
}

However, trying to call the method results in a compilation error:

TS2349: This expression is not callable.
Not all constituents of type 'AssignActionObject<LoaderContext, LoaderEvent> | ActionObject<LoaderContext, LoaderEvent> | ActionFunction<...>' are callable.     
Type 'AssignActionObject<LoaderContext, LoaderEvent>' has no call signatures

Answer №1

Your sample code is experiencing an issue due to the function declaration of actions.fetch, which results in its execution context (the this binding) being determined at runtime based on how it's called. For more details, you can refer to the Mozilla Developer Network reference.

To address this problem, a simple solution would be to declare actions.fetch (as well as other action implementations) as arrow functions, ensuring they are bound to the instance of the LoaderMachine class.

actions: {
    fetch: () => {
      this.fetchDataInsideClass(); // unable to call
      fetchData(); // invoking global declaration works
    },
    restart: () => {
      console.log("Recovering from error");
      service.send("RESTART");
    },
    finished: (context, event) => {
      console.log("Done");
    },
  },

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

Verifying TypeScript errors before each commit in a Vue application

We have set up a git hook in our app using Husky for pre-commit actions. Whenever someone commits code, it triggers the pre-commit code - #!/bin/sh . "$(dirname "$0")/_/husky.sh" export NVM_DIR="$HOME/.nvm" [ -s "$NVM_ ...

Testing a TypeScript function with Jest by mocking a function that is invoked from a separate file

In my code, there is a function called processCosts located in the file prepareStatement.ts. This function makes a call to another function named calculatePrice, which is imported from coreLogic.ts. Within my test file reports.integration.ts, I have impor ...

Preventing over-purchasing products by managing Knex.js inventory levels

Currently, I am in the process of developing an online store for my school's guild organization. I must admit that I lack experience working with databases and Knex.js is still a bit challenging for me. An issue arises when multiple users simultaneo ...

When receiving JSON and attempting to store the data in a variable, I encounter an issue where it returns the error message "undefined is not iterable (cannot read property Symbol

I'm currently integrating the Advice Slip API into my project. I am experiencing an issue when trying to store the JSON data in a variable like so: let advice; fetch("https://api.adviceslip.com/advice").then(response => response.json()). ...

What is the best way to export a default object containing imported types in TypeScript?

I am currently working on creating ambient type definitions for a JavaScript utility package (similar to Lodash). I want users to be able to import modules in the following ways: // For TypeScript or Babel import myutils from 'myutils' // myuti ...

Is there a way to achieve a seamless compilation in TypeScript?

Hopefully this is straightforward! TypeScript Latest version: 1.9.0-dev.20160512 (can be installed using npm install -g typescript@next as suggested by @basarat) Node v5.11.0 Windows 10.0.10586 First file: u1c.ts import * as u1u from "./u1u.ts" let p = ...

Tips for properly utilizing GeolocationPosition in TypeScript

Our goal is to utilize the Geolocation API to access the user's location. This particular code snippet appears to be functioning well: if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position: GeolocationPosition) => conso ...

Toggle visibility between 2 distinct Angular components

In my application, I have a Parent component that contains two different child components: inquiryForm and inquiryResponse. In certain situations, I need to toggle the visibility of these components based on specific conditions: If a user clicks the subm ...

Issue encountered while generating a dynamic listing using Angular

My goal is to generate a dynamic table using Angular. The idea is to create a function where the user inputs the number of rows and columns, and based on those values, a table will be created with the specified rows and columns. However, I am facing an iss ...

Tips for efficiently combining mergeMap observables and providing a singular value for the entire observable

Consider this particular case involving TypeScript/angular with rxjs 6.5: main(){ const items = ['session', 'user']; const source: Observable<any> = from(items); source .pipe( ...

Exploring methods of testing a simple React functional component using Jest, TypeScript, and type annotations

I have been struggling for a long time to find a straightforward example of how to test a simple react component using jest and typescript. Despite my efforts, I have not been successful in finding a solution. I have checked out: https://basarat.gitbooks.i ...

First, download a npm package and integrate it into TSX files

Hello all, I am currently working on my very first project using React, Typescript, and ASP.NET Core. As a beginner in this technology stack, I seek your patience and understanding as I encounter challenges along the way. Right now, I'm facing an issu ...

"Discover the step-by-step process of building a vue.js3 application with typescript, vue-router, and vuex without relying on

I have been assigned the task of developing a Vue3 application with TypeScript support using Vuex for state management and vue-router for basic routing. However, I am not allowed to use vue-cli for this project. Here is my current code: <head> & ...

Encountering a "No overload matches this call" error while using React, Typescript, and d3js

Encountered an error in Typescript while using the scaleLinear() function from d3js. Seeking assistance in resolving this issue. The code is in React and utilizes typescript. Below is the source code: import React, { useRef, useState, useEffect } from &apo ...

Tips for refreshing a component after fetching a new page using the useQuery function

Attempting to retrieve and display data from my custom API using axios and react-query's useQuery. The API incorporates pagination, and I have implemented a table with an option to select the page that displays the current data. Everything functions c ...

When incorporating Papaparse with Angular 2, encountering the issue "Identifier 'Papa' is not found" may arise

Currently, I am facing an issue in my project where after deleting and re-installing node_modules to resolve errors, the definition of 'Papa' is missing. As a result, when npm updated the node modules again, Angular 2 is unable to find 'Papa ...

Specifying the type of "this" within the function body

After going through the typescript documentation, I came across an example that explains how to use type with this in a callback function. I am hoping someone can assist me in comprehending how this callback will operate. interface DB { filterUsers(fil ...

Typedoc does not create documentation for modules that are imported

Whenever I generate documentation with TypeDoc, I am encountering an issue where imported files come up empty. If I add a class to the file specified in entryPoints, I get documentation for that specific class. However, the imported files show no document ...

Issues with Node.js and Socket.io: Receiving error "Cannot read property 'on' of undefined"

I've encountered an issue while trying to establish a websocket connection using socket.io and node.js. Here is the setup I'm working with: Operating System: Windows 7 Node version: 6.9.2 NPM version: 4.0.5 Packages: "express": "^4.14.0" "soc ...

Trigger event when ngModel changes

Currently, I am trying to perform a test on a select element... <select [ngModel]="selectedRouters" name="routerName" class="form-control" id="routersSelect" size="12" (ngModelChange)="selectRouters($event)" multiple> <option [value]="route ...