3

I'm using React-dnd combined with Redux but I can't dispatch an action. My action is called but the reducer is never called :

const spelSource = {
    drop(props, monitor) {
        updateD(monitor.getItem(), props.spel);
    }
};

const mapDispatchToProps = {
    updateD: (newS, oldS) => updateDeck(newS, oldS),
};

export default connect(
    null, mapDispatchToProps
)(Spel)

Spel = DropTarget('spel', spelSource, collect)(Spel);

and in my action :

export function updateD(newS, oldS) {
    console.log("update");
    return function (dispatch) {
        return dispatch({
            type:"UPDATE_D",
            newS: newS,
            oldS: oldS
        });
    };
}

Finally the reducer :

    case 'UPDATE_D':
        return Object.assign({}, state, {
            d: finalUpdate(state, action)
        });

Is there a way to dispatch? Thanks!

Zeyukan Ich'
  • 651
  • 7
  • 21
  • 1
    You can replace that mapDispatchToProps with `const mapDispatchToProps = { updateDeck };` quite simpler. – enapupe Jan 31 '19 at 14:41

3 Answers3

4

You are trying to dispatch from the action, but you need Redux to dispatch the action itself. Your action should just return an object with type property and payload (whatever else). The action gets wrapped in the dispatch() function by the connect() function with mapDispatchToProps. Traditionally, you do like this...

const mapDispatchToProps = dispatch => ({
  updateD: (newS, oldS) => dispatch(updateDeck(newS, oldS))
});

There are some shorter ways to do this in this article, but this is the traditional way. You can see that the connect() function takes this and will pass it through the dispatch() method of the Redux store.

Then, your action will just return the object:

export const UPDATE_D = 'UPDATE_D';

export const updateD = (newS, oldS) => ({
    type: UPDATE_D,
    newS,
    oldS
});

Finally, your reducer:

switch (action.type) {
  case UPDATE_D:
    return {
      ...state,
      newS: action.newS,
      oldS: action.oldS
     };
     default:
       return state;
   }
Justin Reusch
  • 624
  • 7
  • 14
2

You need to use this.props to properly dispatch that action from your component.

E.g, in spelSource, this.props.updateD(monitor.getItem(), props.spel)

rustyshackleford
  • 692
  • 1
  • 7
  • 22
1

may be an error that action returns a function instead of object. And this inner function is never called.

I would expect to see something like:

const mapDispatchToProps = dispatch => {
  return {
    updateD: (newS, oldS) => dispatch({
            type:"UPDATE_D",
            newS: newS,
            oldS: oldS
        })
  }
}

Shevchenko Viktor
  • 5,206
  • 2
  • 17
  • 26