How to write an action creator for submitting a form asynchronously

0 votes
Can you tell me How to write an action creator for submitting a form asynchronously?
Mar 17 in Node-js by Nidhi
• 12,580 points
67 views

1 answer to this question.

0 votes

To write an action creator for submitting a form asynchronously in Redux, use Redux Thunk. Here's a concise example:

1. Install Redux Thunk

Ensure Redux Thunk is set up in your store.

2. Define the Async Action Creator

Example:

export const submitForm = (formData) => async (dispatch) => {

  dispatch({ type: 'SUBMIT_FORM_START' }); // Indicate start

  try {

    const response = await fetch('/api/submit', {

      method: 'POST',

      body: JSON.stringify(formData),

      headers: { 'Content-Type': 'application/json' },

    });

    const data = await response.json();

    dispatch({ type: 'SUBMIT_FORM_SUCCESS', payload: data }); // Success

  } catch (error) {

    dispatch({ type: 'SUBMIT_FORM_FAILURE', payload: error.message }); // Error

  }

};

3. Handle Actions in Reducer

Example:

const initialState = {

  loading: false,

  success: false,

  error: null,

};

const formReducer = (state = initialState, action) => {

  switch (action.type) {

    case 'SUBMIT_FORM_START':

      return { ...state, loading: true, success: false, error: null };

    case 'SUBMIT_FORM_SUCCESS':

      return { ...state, loading: false, success: true };

    case 'SUBMIT_FORM_FAILURE':

      return { ...state, loading: false, error: action.payload };

    default:

      return state;

  }

};

export default formReducer;

4. Dispatch in Component

Example:

import React, { useState } from 'react';

import { useDispatch, useSelector } from 'react-redux';

import { submitForm } from './actions';

const FormComponent = () => {

  const dispatch = useDispatch();

  const { loading, success, error } = useSelector((state) => state.form);

  const [formData, setFormData] = useState({});

  const handleSubmit = (e) => {

    e.preventDefault();

    dispatch(submitForm(formData));

  };

  return (

    <form onSubmit={handleSubmit}>

      <input

        type="text"

        value={formData.name}

        onChange={(e) => setFormData({ ...formData, name: e.target.value })}

      />

      <button type="submit" disabled={loading}>

        {loading ? 'Submitting...' : 'Submit'}

      </button>

      {error && <p>{error}</p>}

      {success && <p>Form submitted successfully!</p>}

    </form>

  );

};

export default FormComponent;

answered Mar 18 by Tanvi

Related Questions In Node-js

0 votes
1 answer

How to create an action creator for fetching data in Redux?

To create an action creator for fetching ...READ MORE

answered Mar 18 in Node-js by Anvi
45 views
0 votes
0 answers
0 votes
1 answer

How to write a test which expects an Error to be thrown in Jasmine?

Hello @kartik, Try using an anonymous function instead: expect( ...READ MORE

answered Jul 13, 2020 in Node-js by Niroj
• 82,840 points
9,805 views
0 votes
1 answer

How to improve user experience in React using async workflows?

It involves optimizing how your application handles ...READ MORE

answered Mar 18 in Node-js by Anvi
43 views
0 votes
1 answer
0 votes
1 answer

How to handle pending, fulfilled, and rejected states in async reducers?

With Redux Toolkit (Built-in Handling): Use createAsyncThunk to ...READ MORE

answered Mar 18 in Node-js by Tanvi
61 views
0 votes
1 answer

How to update state based on async action outcomes in reducers?

To manage asynchronous actions (e.g., API calls), ...READ MORE

answered Mar 18 in Node-js by Tanvi
77 views
0 votes
1 answer

How can I check if an array contains a particular string in TypeScript?

You can use includes() method, which checks ...READ MORE

answered Feb 10 in Node-js by Navya
88 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP