Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux not dispatching action

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!

like image 415
Zeyukan Ich' Avatar asked Jul 14 '26 12:07

Zeyukan Ich'


2 Answers

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;
   }
like image 82
Justin Reusch Avatar answered Jul 16 '26 04:07

Justin Reusch


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)

like image 21
rustyshackleford Avatar answered Jul 16 '26 03:07

rustyshackleford