0

Here is my store, implemented thunk:

store/index.js

import { createStore, applyMiddleware } from "redux";
import reducer from "../reducers/";
import thunk from "redux-thunk";

const store = createStore(reducer, applyMiddleware(thunk));
export default store;

here is my action:

actions/index:

export const remove = function(id) {
  return {
    type: "remove",
    payload: setTimeout(function() {
      return id;
    }, 2000)
  };
};

export const add = function() {};

export default { remove, add };

here is my dispatch function:

component/Item.js

import React from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { remove } from "../actions/";

const Item = props => {
  function removeTrigger() {
    props.remove(props.item.id);
  }
  return (
    <li>
      {props.item.name} <button onClick={removeTrigger}>Delete</button>
    </li>
  );
};

function mapAction(dispatch) {
  return bindActionCreators({ remove }, dispatch);
}

export default connect(
  null,
  mapAction
)(Item);

on click on delete button I am getting a console message. But the id is not removed. any one help me to implement the thunk advantage properly here?

Live Demo

1 Answer 1

1

Thunk is a middleware that acts whenever you pass a function to an action creator instead of an object. So to dispatch async code, assuming that your component is correctly connected and mapping dispatchToProps your async action creator should look something like this:

     export const remove = function(id){
         return function(dispatch){
             let id = null
             setTimeout(()=> {
                id = 1
                dispatch({type: 'remove', payload:id})
             }, 3000)
         }
    }

You can also receive an extra argument beside dispatch, a getState function that allows you to access the global state.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please update my demo as sample, not able to understand properly
Your remove function it's what we call an actionCreator, that is exactly that: A function that returns an action(object with a type property) to the reducer. All the code passed to a reducer by definition MUST be synchronous. In your case you are returning async code to you reducer in payload. This is hapenning because thunk will only act when your action creator return a function instead of an object, and inside this function, after the async code have finished then you dispatch the object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.