Transforming a redux form onSubmit function into a promise-based structure

One of my goals is to promisify the onSubmit handling in my submitForm for redux form.

You can find a similar example here.

submitForm = () => {
     return this.props.submituserForm() 
        .then(() => { console.log('test') })
        .catch(() => { console.log('error') })
}

-----------------------------------


const mapDispatchToProps = (dispatch) => {
    // I aim to convert submituserForm into a promise-like function mimicking the sleep 
    // function featured below
    return {
        submituserForm: () => dispatch(submit())
    }
};

//////////////////////////////////////////////////// 


// This section is functioning correctly
const submit = () => {
    const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

    // Introducing server latency simulation
    return sleep(5000)
        .then(() => { console.log('test') };
}

Answer №1

It seems like you might be approaching this issue from the wrong angle. The redux-form library already includes a feature for managing promises when submitting a form. According to the documentation:

If your onSubmit function returns a promise, the submitting property will indicate its status until the promise is resolved or rejected. If it's rejected with a redux-form SubmissionError containing errors in the form { field1: 'error', field2: 'error' }, those submission errors will be displayed for each field (in the error prop) similar to async validation errors. For non-specific errors applicable to the entire form, treat them as an error for a field named _error, and it will be set as the error prop.

The following code snippet demonstrates this concept:

// submit.js
import { SubmissionError } from "redux-form";

export const submit = (values, dispatch, props) => {
    const simulateServerLatency = ms => new Promise(resolve => setTimeout(resolve, ms));

    // simulate server latency
    return simulateServerLatency(5000)
        .then(() => { console.log('test') })
        .catch(() => {
            console.error('error');
            throw new SubmissionError({ _error: 'There was an error submitting.' });
        });
}

// MyForm.js
import React from "react";
import { reduxForm, ... } from "redux-form";
import { submit } from "submit";

class MyForm extends React.Component {
    ...
    render() {
        const { error, handleSubmit } = this.props;
        return (
            <form onSubmit={handleSubmit}>
                ...
                {error && <strong>{error}</strong>}
                <button type="submit" value="Submit">Submit</button>
            </form>
        )
    }        
};

export default reduxForm({
    form: "MyForm",
    onSubmit: submit
})(MyForm);

For a more comprehensive guide on handling promises during form submission, refer to this example.

Answer №2

In order for dispatch(submit()) in react-redux to return a Promise, the function submit() needs to be modified to return a thunk:

const submit = () => {
  return (dispatch, getState) => {
    const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

    // simulate server latency
    return sleep(5000)
      .then(() => { console.log('test') };
  }
}

Currently, the function is returning a Promise directly instead of a function that returns a Promise, which is necessary for redux-thunk functionality.

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

Steps to resolve the issue: The 'jsx' functionality is not activated at the moment

I recently started working with ReactJS and I came across a similar error message in this post: Syntax Error: Support for the experimental syntax 'jsx' isn't currently enabled. Despite reading it, I am still unable to solve my issue. When I ...

Adding a text field on top of a div based on the dropdown value selection

I am working with a dropdown option inside a div. I want to make it so that when the last option is selected, a text box will appear on top of the dropdown. And when a different option is selected, the text box should be disabled. How can I achieve this? ...

What is the reason behind not being able to utilize addEventListener on a variable that has been selected through DOM's getElementsByClassName method?

btn = document.getElementsByClassName('btn'); value = document.getElementById('value'); let counter = 0; btn[2].addEventListener('click', function() { if (btn[2].classList.contains('decrease')) counter -= 1; if ...

Content Security Policy Error triggered by Iframe Source Running Script in Web Extension

My web extension for Firefox utilizes a content script to add HTML to a webpage when a button is clicked. The injected HTML includes an iFrame nested in multiple div elements. Below is the relevant part of the content script: var iFrame = document.create ...

a guide on utilizing knockout js to bind json data within a datalist

Below is the code I have written for my web services: public class SympsService : System.Web.Services.WebService { [WebMethod] public symps GetSymptoms(string organ_name) { symps Symptoms = new symps(); string CS = Configurati ...

What's the best way to display my slider exclusively on the homepage?

Hello, I am experiencing an issue with my slider. I would like to display the slider only on the home page and not on any other sub-pages. Is there a way to achieve this? Below is the code that I am using: <script> $( ...

Explore various date formats using the datepicker functionality

I'm dealing with the code below: <script type="text/javascript" language="javascript" src="~/Scripts/bootstrap-datepicker.min.js"></script> <script type="text/javascript" language="javascript" src="~/Scripts/locales/bootst ...

Pass the JavaScript variable and redirect swiftly

One of the functionalities I am working on for my website involves allowing users to submit a single piece of information, such as their name. Once they input their name, it is sent to the server via a post request, and in return, a unique URL is generated ...

Tips for retrieving data from a database with just one key press

There is a text field that triggers a JavaScript function when a key is pressed. <input type="text" class="text" id="txt_sh_vid" onKeyPress="vhc_record()" maxlength="4"> The function takes the input from the text field and searches for a result in t ...

Access information from Google Sheets through an AJAX GET request

I am facing an issue with my code while trying to retrieve data from a Google spreadsheet that I have already published. I have set the share properties of the spreadsheet to 'anyone can edit' and provided the correct URL, but I am still encounte ...

Failed to transfer form data to server using ajax in Node.js

I am attempting to utilize AJAX to send form data to a Node.js server. I had previously inquired about this on the following post. Below is a glimpse of my code: <div id="inputid" style="width: 400px; height:400px"> <p> Kindly input value ...

Tips for identifying selected rows in Material UI DataGrid

Currently, I am in the process of developing a website using React along with Material UI. My main focus right now is to identify which rows are currently selected in my DataGrid. To achieve this, I want to populate an array with the selected rows using t ...

Troubles with setting up node modules in a Windows 10 environment

I'm encountering difficulties when trying to install modules on my Windows 10 laptop after setting up Node.js from scratch. Since it's my personal computer, I have complete control over the system. Despite searching through various online forum ...

Error 400: Invalid Request: Issue encountered when swapping code for Asana access token using Next.js

Encountered a 400 Bad Request error while trying to exchange the code for an access token at . I am unsure of the cause and would appreciate any assistance. Below is the code: const GetAsanaAccessToken = async (req, res) => { const body = { grant ...

Leveraging nodemailer for automated email delivery

Hey there! I'm looking for some advice on how to set up scheduling with emailing using nodemailer. Ideally, I'd love to be able to schedule emails to send every day at 9am within a web app using nodemailer. However, I'm not sure where to st ...

Obtain the file path and store it in a variable right after using fs.writefile

Can anyone assist me in obtaining the file path of the created file in the following code snippet? I am passing a barcodeSourceNumber as a parameter and expecting the file path as the return value. pathToFile = generateBarcodeImage('123456789'); ...

Querying a collection with a bulk request using Mongoose Cursor

My current challenge involves working with rxJS and handling bulk HTTP requests from a database containing over 1 million documents. The code I have is relatively simple. I am pushing all the documents from the collection into an array called "allPlayers" ...

Unveiling the Technique: Adjusting Field Visibility When Dropdown is Altered

I tried to find a solution on Stackoverflow for displaying/hiding a field based on dropdown selection using either jQuery or inline JavaScript. However, I am facing difficulties when implementing this within a table. Let's start with an easy approach ...

Using Switch Case and If Statements in Javascript and Jquery

Can you help me troubleshoot this code? It's designed to detect clicks and keypress events within the #ts_container div for buttons and anchors. The goal is to use an If statement in each case to determine if it's a click or keypress, then update ...

The operation of moveImage does not exist

Currently, I am attempting to incorporate setInterval with my moveImage function in order to modify the position of an image. Here is a snippet of my code: <template> <div class="randImg"> <img v-bind:style="{top: imgTop + 'px&ap ...