What is the best way to create a promise in a basic redux action creator?

My function add does not return any promises to the caller.

Here's an example:

let add = (foo) => {this.props.save(foo)};

In another part of my application, I want to wait for add() to finish before moving on to something else. However, I know that the async save function does not return a promise, as it is a simple Redux action.

...
return  add()
        .then( ... do something else here ... );
 export const save = (something) => (dispatch) => {

  ApiUtil.patch(`google.com`, { data: { 
 something  } }).
   then(() => {
  dispatch({ type: Constants.SET_FALSE });
  },
() => {
  dispatch({ type: Constants.SET_SAVE_FAILED,
    payload: { saveFailed: true } });
});
};

I have included this code snippet to demonstrate the action being taken.

Answer №1

It appears that you are utilizing redux-thunk for handling asynchronous actions, as your add action creator is returning a function that takes in dispatch instead of a simple action object.

If redux-thunk is indeed being used, the value you return from your thunk will be passed back out. Therefore, if you make changes to your code like so:

let add = (item) => this.props.save(item); // Now returns save result

You should then modify your thunk to:

export const add = (something) => (dispatch) =>
    ApiUtil.patch(`example.com`, { data: { something } })
        .then(() => { dispatch({ type: Constants.SET_FALSE }); },
            () => { dispatch({ type: Constants.SET_SAVE_FAILED, payload: { saveFailed: true }});}
        );

(Note the removal of the outermost curly braces), allowing the promise from ApiUtil to propagate all the way up and enabling you to use .then on it.

Answer №2

Before proceeding, it is important to have a clear grasp on the output of this.props.save(). In case it returns a promise, simply return it within the add function:

const add = (bar) => { return this.props.save(bar); }

The main issue lies in understanding the exact functionality of the save method.

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

Avoid activating ng-blur when ng-keydown is triggered in AngularJS

Currently, I am working on a project involving angularJS and I am facing an issue with the execution of ng-blur conflicting with ng-keydown. The problem arises because ng-keydown causes the element to lose focus at a certain point. The HTML code in questi ...

Function in Node.js/JavaScript that generates a new path by taking into account the original filepath, basepath, and desired destination path

Is there a custom function in Node.js that takes three arguments - filePath, basePath, and destPath - and returns a new path? For example: Function Signature Example var path = require('path'); // Could the `path` module in Node be useful here? ...

Resolving parent routes in Angular 2

I am encountering an issue with my code. The 'new' route is a child route for the 'users' route. The 'users' route has a resolver, and everything works fine up to this point. However, after successfully creating a new user, ...

Triggering successive jQuery confirm boxes once the previous one has finished processing

I am facing an issue with my API call response where I receive an array and need to open jQuery Confirm one by one for each item in the response. The problem is that they all open at once. Below is the code snippet: axios.post('/orders/ask-for-or ...

I would like the capability to choose a roster of gods depending on a character's class and moral orientation

I am in the process of developing a character sheet for Dungeons & Dragons, and I'm looking to pass the values from two drop-down menus into a query that will then populate another select list. Despite trying various methods to retrieve the data, I ke ...

Adding two unique identifiers together using Ajax can be easily accomplished by sending a request

I have implemented an Ajax function to display auto suggestions in a search field. However, I have two search fields on the same page and when I try to use the function, it only works for one of the fields. This is because both fields have the same ID and ...

Determining whether a PFUser is being created or updated with the AfterSave function

Struggling to differentiate between whether a PFUser is being updated or saved for the first time? I tried implementing a solution from parse.com here, but it's not working as expected. No matter what, I always end up with a false value, be it an init ...

What is the best way to implement conditional hook usage in React?

Having two hooks at my disposal, useLocalStorage and useQuery, I find myself wondering about conditionally utilizing one of them based on an input prop. I'm considering writing the following: const [value, setValue] = localStorage ? useLocalStorage() ...

Are the events objects failing to render or is the scope not being broadcasted properly

I'm having trouble displaying my events using the ionic-calendar plugin by calling the $scope.loadEvents method. Unfortunately, the events are not showing up on the calendar. Here is the link to the plugin I am using: https://github.com/twinssbc/Ioni ...

Is there a way to utilize a single function on two separate div elements?

Looking for a way to optimize my code that contains the addRow() and deleteRow() functions. Currently, I have duplicated these functions for both radio buttons and checkboxes. Is there a more efficient way to achieve this? function addRow(tableID) { ...

Generate a custom image using a pre-existing background image and text using JavaScript, then save it as a JPEG file in

Managing multiple fanpages on Facebook can be quite a task, especially when it comes to posting images with funny text. I have different backgrounds for each page, which means I have to save each image individually with the text. To streamline this process ...

Managing state changes with a slider in ReactJS

I am currently working with the Foundation slider found at this link: click for doc. To access the slider's current value, they recommend using a hidden input like this: <div class="slider" data-slider data-initial-start="50" data-end="200"> & ...

The regex pattern did not match the line of code in the Node.js script

I need help finding a regex pattern that can identify any line of code containing just one reference to a core module. Here is an example: const coreModuleMatches = /'^[var|const]{0,1}[a-z\$\_]{1,}=require([\'|"][assert|fs|path][ ...

I am utilizing Vue.js to create a duplicate input field and dynamically increasing the index

When a user clicks on the "add another" button, I want to create a duplicate text input field and increase the index of the new field. I found this question that is similar, but the solution provided did not successfully increment the index. The current i ...

JavaScript makes it possible to access subnodes in XML by utilizing specific methods and

I am looking to utilize javascript to extract data from an XML file that has been loaded into a webpage. Below is the XML file (a.xml) that I am working with. a.xml <?xml version="1.0"?> <Step rID="T6"> <Obj ><![CDATA[Get Data Ta ...

Guide to dynamically incorporating items from an array into the filter operation

How can I dynamically insert items from an array into the filter on the wizard.html page, so that when the templateUrl in the route is called, it can be rendered on the wizard.html page? Controller angular.module('tareasApp') .controller(&apo ...

What is the technique for defining sub paths in React-Router-Dom by excluding the parent path?

Imagine a Profile page that displays different components based on the path it receives. For example: /profile/posts will show the Posts component within Profile. /profile/comments will display the Comments component inside Profile. Typically, the Profi ...

The functionality of Bootstrap Tabs is compromised when used within a jQuery-UI dialog window

My goal is to develop a user interface similar to MDI for my application. To achieve this, I am utilizing the dialog feature of the jQuery UI library. To dynamically create a dialog window on demand, I have coded a helper function as shown below: functio ...

A guide on effectively utilizing ref forwarding in compound component typing

I am currently working on customizing the tab components in Chakra-ui. As per their documentation, it needs to be enclosed within React.forwardRef because they utilize cloneElement to internally pass state. However, TypeScript is throwing an error: [tsserv ...

Troubleshooting permission problems with Yarn and node_modules in a Docker environment

I have a Docker container containing a Symfony 6 web application and various other services like php-fpm, node, and python. Additionally, I have separate containers for MySQL and Nginx, all running on Alpine 3.15. My current issue arises when I execute do ...