How to write an action creator that returns a function using redux-thunk

0 votes
With the help of code can you tell me How to write an action creator that returns a function using redux-thunk?
Mar 17 in Node-js by Nidhi
• 12,580 points
69 views

1 answer to this question.

0 votes

Using redux-thunk, an action creator can return a function that receives dispatch (and optionally getState) to perform async operations.

Example:

const fetchData = () => {

  return async (dispatch) => {

    dispatch({ type: 'FETCH_START' });

    try {

      const res = await fetch('/api/data');

      const data = await res.json();

      dispatch({ type: 'FETCH_SUCCESS', payload: data });

    } catch (error) {

      dispatch({ type: 'FETCH_ERROR', error });

    }

  };

};

answered Mar 18 by Anvi

Related Questions In Node-js

0 votes
0 answers
0 votes
0 answers

How to manage async API calls in a React app using redux-thunk?

Can you tell me How to manage ...READ MORE

Mar 19 in Node-js by Ashutosh
• 23,230 points
29 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,802 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
40 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
56 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
74 views
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
43 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