I'm looking for a way to create a Redux thunk action creator that will return a promise. How

In my code, I have a primary thunk that is triggered by a button click. Within this thunk, I need to invoke another thunk and ensure it completes before proceeding. The second thunk returns a promise.

Below is an excerpt of the code in question:

export function mainThunk(): ThunkAction<void, void, void, AnyAction> {
    return (dispatch: Dispatch<any>) => {
    ...perform some actions
    dispatch(secondThunk()).then(() => {
     ...continue with other actions
     })
    };
}

export function secondThunk(): ThunkAction<Promise<any>, void, void, AnyAction> {
    return (dispatch: Dispatch<any>) => {
      return new Promise((resolve: any, reject: any) => {
        executeSomeAsyncFunction()
        .then((response) => {
           return Promise.all(someArray.map(someId => {
             return executeAnotherAsyncFunction(someId):
         }));
        })
        .then((responses) => {
           responses.foreach(response => {
             dispatch(dispatchReduxAction(response.someField));
           });
        })
        .then(() => {
          resolve();
        });
    });
    };
}


While the code appears to function correctly during runtime, I encounter a compilation error stating:

Property "then" does not exist on type "ThunkAction<Promise<any>, void, void, AnyAction>"

I've reviewed various Stack Overflow threads but haven't been able to pinpoint why TypeScript is flagging this as incorrect. If you have any insights or suggestions, they would be greatly appreciated!

Answer №1

Discovered the solution. When utilizing the thunk middleware, your dispatch function transforms into a ThunkDispatch as opposed to a regular Dispatch. Fortunately, Typescript handles this automatically, so there's no need to explicitly type the dispatch function. Simply removing the type declaration on dispatch resolves the issue. See example below:

export function mainThunk(): ThunkAction<void, void, void, AnyAction> {
    return (dispatch) => {
    ... perform some actions
    dispatch(secondThunk()).then(() => {
     ... carry out additional tasks
     })
    };
}

export function secondThunk(): ThunkAction<Promise<any>, void, void, AnyAction> {
    return (dispatch) => {
      return new Promise((resolve: any, reject: any) => {
        someAsyncFunction()
        .then((response) => {
           return Promise.all(someArray.map(someId => {
             return someOtherAsyncFunction(someId):
         }));
        })
        .then((responses) => {
           response.foreach(response => {
             dispatch(someReduxAction(response.someField));
           });
        })
        .then(() => {
          resolve();
        });
    });
    };
}

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

Tips on altering a predetermined input text value using JavaScript

I have a question about using JavaScript. I am currently developing a tax calculation system. function calculateTax(){ var invoiceValue = document.getElementById("invoicevalue"); var ppn = document.getElementById("ppn"); var pph = document.get ...

"NameService is not provided in Angular, please check your module

I've been struggling with loading a class into my Angular component. I've spent quite some time trying to figure out the solution, even attempting to consolidate everything into a single file. Here is what I have: Application.ts /// <referenc ...

Reload entire page for AJAX request if JavaScript is not enabled

Currently utilizing JSF2. I have a button that triggers an action and then updates a section of the page (fairly standard). <h:commandButton value="foo" action="#{myBean.myAction}" > <f:ajax execute="@form" render="#content" /> ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...

What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference. if ($(window).width( ...

Grab the source attribute of the <img> tag (identified by class) across numerous HTML pages

Here is an example: A website has the URL , where xxxx represents an integer between 1 and 1935. On each page, there may be an <img class="thumbnail" src="Images\Robots\{robotname}.png">. However, not all pages have th ...

Passing data in Angular 4 with eventEmitter across multiple layers of components

Struggling with a challenge in Angular and need some guidance. I am currently working with Angular 4 and here is the scenario: The app.component.html file contains a wrapper div that I want to be able to change its color by adding a class to it. However ...

Tips for determining the actions of a node prior to its inception

Is there a way to automatically run scripts on specific elements after their creation? For example, using a jQuery plugin like autoresize to expand the height of a textarea. If I use $('.textarea').autosize(), only the current textareas will be a ...

Exploring the intricacies of pattern matching with JavaScript visualization

I am currently working on improving my pattern matching function by creating a visualizer for it. To achieve this, I need to slow down the execution of each comparison. My approach involves declaring the i and j variables outside of the function so that I ...

Key in the calculation on Keypup for multiple rows, one row at a time

I want to create a calculation function for a form with multiple rows. The goal is to determine the totals for each row by multiplying the cost and unit price, then inputting the result in the total field. Below is the script that I attempted: <scrip ...

The JavaScript array on its second usage had a length of '0', yet it still contained objects within it

About the Task: This task involves working with two arrays: arrNumber, which is a number array, and arrString, which is a string array. The goal is to create a list of objects using the values from arrNumber, where the object keys are numbers or characte ...

What is causing the click function to malfunction after selecting a second item?

I'm struggling to understand why my click function isn't functioning properly. You can view the JSFiddle here: http://jsfiddle.net/adbakke/ve9oewvh/ This is a condensed version of my HTML structure: <div class="projectDisplay"></div&g ...

Security Vulnerability in Ajax Callback Breakpoints

Imagine I have the following code snippet (partially pseudocode) $.ajax({ url: "/api/user", success: function(resp) { var data = JSON(resp) if (data.user.is_admin) // do admin thing else // do somet ...

Adjust the color of static hyperlinks based on the background color

Is there a way to dynamically change the color of my fixed side links based on the background color when scrolling? I attempted to use CSS mixed-blend-mode: difference, but it does not provide the level of control I need. Therefore, I am looking to achieve ...

What's the quickest method for duplicating an array?

What is the quickest method for duplicating an array? I wanted to create a game, but I found that Array.filter was performing too slowly, so I developed a new function: Array.prototype.removeIf = function(condition: Function): any[] { var copy: any[] ...

Implementing a Typescript hook using useContext along with an uninitialized context object

I am currently attempting to develop a custom hook called useAuth in React 17 with TypeScript. While my solution is somewhat functioning, it requires the following syntax when utilizing the hook methods: const auth = useAuth(); // Do other stuff ...

Transferring an IONIC project to a different computer

Let me outline the current situation I am facing - I primarily work as a firmware developer rather than a software developer. Recently, a team member who was responsible for developing the front end of an application in IONIC has left the company, leaving ...

Changing an object into an array for saving and transforming it back to an array for usage in JavaScript

I am dealing with a unique situation where I have an object created from dynamic checkboxes in Angular. The structure of the object looks like this: {"United States":true,"Canada":true,"Australia":false} While this format works well for storing values, I ...

Encountering a problem retrieving the .ClientID property in ASP.NET using C#

In my uploadError javascript function for AsyncFileUpload from AJAX toolkit, I have the following code snippet: function uploadError(sender, args) { document.getElementById("<%# uploadResult.ClientID %>").innerText = args.get_fileName(), "<sp ...

What could be causing replace() to malfunction in Node.js?

I am dealing with some data in Node.js and I am trying to replace the ampersands with their escape key. Below is the code snippet I am using: let newValue = data; for (label in labelData.data) { let key = "Label " + label; newValue = newValue.rep ...