Patience is key when hoping for a reaction nested within another in Redux

I am attempting to recycle one of my actions. Here is the structure of my actions:

const actions = {
changeStage: (data: Object) => (dispatch) => {
        return new Promise((resolve) => {
            dispatch({type: ACTION_TYPES.Loader, payload: "Loading"});
            resolve();
        })
        .then(() => {
            return serviceCallToChangeStage(data); 
        })
        .catch((str: string) => {
            dispatch({type:ACTION_TYPES.error, payload: str});
        });
    }

I intend to reuse the above action in another action as shown below:

changeStageAndSaveData: (data: Object) => (dispatch) => {
        return new Promise((resolve) => {
            dispatch({type: ACTION_TYPES.Loader, payload: "Loading"});
            resolve();
        })
        .then(() => { //This is where I want to re-use
            if(certainCondition){
                return actions.changeStage(data);
            }
        }
        .then(() => {
            return saveDataThroughServiceCall(data); 
        })
        .catch((str: string) => {
            dispatch({type:ACTION_TYPES.error, payload: str});
        });
    }

When I try to do return actions.changeStage(data), it does not execute for some reason. If I dispatch on that actions.changeStage(), the second service call starts immediately without waiting for the previous call to finish. Since both my actions are enclosed in promises, I assume they should be reusable with a return statement. What am I overlooking?

Answer №1

Below are some steps you can take:

const actions = {
  changeStage: (data: Object) => (dispatch) => {
    //perform dispatch which is not asynchronous, no need for promise yet
    dispatch({
      type: ACTION_TYPES.Loader,
      payload: 'Loading',
    });
    //assuming serviceCallToChangeStage returns a promise
    return serviceCallToChangeStage(data).catch(
      (str: string) => {
        dispatch({
          type: ACTION_TYPES.error,
          payload: str,
        });
      }
    );
  },
  changeStageAndSaveData: (data: Object) => (dispatch) => {
    //no need to create promise at this point
    dispatch({
      type: ACTION_TYPES.Loader,
      payload: 'Loading',
    });
    //can return a promise here
    return Promise.resolve(
      certainCondition &&
        actions.changeStage(data)(dispatch)
    )
      .then(() => saveDataThroughServiceCall(data))
      .catch((str: string) => {
        dispatch({
          type: ACTION_TYPES.error,
          payload: str,
        });
      });
  },
};

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 correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

Modifying app aesthetics on-the-fly in Angular

I am currently working on implementing various color schemes to customize our app, and I want Angular to dynamically apply one based on user preferences. In our scenario, the UI will be accessed by multiple clients, each with their own preferred color sch ...

Bring in exclusively typescript module declarations

In my various React projects, I find myself constantly declaring the same typescript modules, such as fonts.d.ts: declare module "*.woff"; declare module "*.woff2"; or images.d.ts: declare module "*.jpg" { const src: string ...

What are the steps to creating an Observable class?

I am working with a class that includes the following properties: export class Model { public id: number; public name: string; } Is there a way to make this class observable, so that changes in its properties can be listened to? I'm hoping fo ...

There is an issue with the Hook call on the component list map in ReactJS

While working on Review components, I encountered an error when trying to use hooks. Here is the issue: I am using YhSection to manage my parallel components and utilizing array map to incorporate them in the layout content. Interestingly, if I use hoo ...

Redux Saga effect does not have a matching overload for this call

Encountering an error in my Redux Saga file, specifically when using the takeLatest() Saga effect. TypeScript is throwing the following error: (alias) const getMovies: ActionCreatorWithoutPayload<string> import getMovies No overload matches this call ...

The JSX element 'HeaderPublic' does not contain any construction or calling signatures

I am currently utilizing nx workspace to build the react ts application. Below is the library component: import { ReactElement } from 'react'; import styles from './header-public.module.scss'; export function HeaderPublic(): ReactElem ...

What is the best way to obtain a signed cookie in aws-sdk-js-v3?

I am looking to utilize signed cookies for accessing private content stored on S3 using CloudFront for CDN. I am struggling to identify the appropriate commands to generate signed cookies in aws-sdk-js-v3. According to the updated SDK documentation, it sh ...

It’s not possible for Typescript to reach an exported function in a different module

Having trouble referencing and using exported methods from another module. I keep getting an error that says 'There is no exported member in SecondModule'. module FirstModule{ export class someClass{ constructor(method: SecondModule ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

The pipe property cannot be accessed for the specified type "OperatorFunction<unknown, [unknown, boolean, any]>"

I have set up a data subscription that I want to utilize through piping, but for some reason it's not working as expected. The error message I'm receiving is: The property pipe is not available for type "OperatorFunction<unknown, [unknown, b ...

No matter the circumstances, the "Unexpected end of form" error consistently appears when attempting to upload files in Express

I'm facing a challenge in implementing a file upload API endpoint for my Express+no-stress+Typescript application. Initially, I attempted to use the express-fileupload library, but I quickly realized that it didn't integrate well with Typescript ...

Encountering Problem with NextJS and Typescript when Attempting to Import Protected Authentication to a Page

When I try to use my protected.tsx file on a page, I encounter an error message stating: Server Error Error: Attempted to call the default export of protected.tsx from the server, but it should only be used on the client side. Invoking a client function ...

I am experiencing difficulties with my Angular 8 NPM package as it is unable to locate its own

I am encountering an issue where my assets are successfully copied over to my scoped npm package, but they are not available after the application is served. Currently, the images in my application are searching for a path like this: https://localhost:420 ...

Conceal a row in a table using knockout's style binding functionality

Is it possible to bind the display style of a table row using knockout.js with a viewmodel property? I need to utilize this binding in order to toggle the visibility of the table row based on other properties within my viewmodel. Here is an example of HTM ...

What's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3 Consider the following JSON data: const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } To update the title using spread synta ...

Dealing with Typescript: Reducing an object containing other objects

Having some difficulties implementing a reduce function with TypeScript - struggling with types and return value. Facing issues with omitting controls from Storybook, causing two TypeScript errors indicated in the code marked ** ERROR ** Seeking advice on ...

Utilizing an array for substituting sections of a string: a guide

I have an array of values like ['123', '456', '789']. What is the best way to iterate over this array and update parts of a string that contain the text :id in sequence (e.g. users/:id/games/:id/server/:id)? Currently, I&apos ...

Feathers.js - Error: Property 'feathers' is missing from the 'Socket' type

Trying to include a property in a socket connection to identify the user and send a response solely to that individual. Came across a potential solution at: How to add parameters to a FeathersJS socket connection Unfortunately, the solution doesn't s ...

Tips for including type definitions when adding elements to an array in TypeScript

Having trouble avoiding the use of 'any' as the type definition when pushing elements into an array? I attempted to specify the type but encountered an error. Here is a snippet of the code: interface answerProps { state: string; answer: s ...