Drew Drew - 3 months ago 18
React JSX Question

Redux Callback after dispatching an action?

So in my React component, I have this:

this.props.updateAlert({
type: 'error',
message: ERROR_MESSAGE
}, () => {
console.log('callback');
})


My
updateAlert
action is:

export const updateAlert = (alert, fn) => {
let data = {
type: 'UPDATE_ALERT',
alert
}

if(data) {
return fn(data)
}

fn();
}


I'm getting the following error: Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

I tried to look at
redux-thunk
but couldn't quite figure out how to implement it with my setup.

My main app component has this:

const mapDispatchToProps = (dispatch) => {
return bindActionCreators(actionCreators, dispatch);
}

const App = connect(mapStateToProps, mapDispatchToProps)(Main);

export default App;


And my main store has this:

const enhancers = compose(
window.devToolsExtension ? window.devToolsExtension() : f => f
);

const store = createStore(rootReducer, defaultState, enhancers);

// we export history because we need it in `reduxstagram.js` to feed into <Router>
export const history = syncHistoryWithStore(browserHistory, store);

export default store;


I think with all the examples I looked at, the
createStore
statement was a bit different from mine, and all of their examples were fetching some API so then they could attach a
.then()
function after it. I'm having a difficult time trying to figure out the best solution for this specific scenario.

Update: I got it to work, there was an issue with my store code and how my middleware was being called. This ended up working:

const store = createStore(
rootReducer,
defaultState,
compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f,
)
)

Answer

Redux-thunk is your answer. In your store code change

const enhancers = compose(
  window.devToolsExtension ? window.devToolsExtension() : f => f
);

to

const enhancers = compose(
  window.devToolsExtension ? window.devToolsExtension() : f => f,
  applyMiddleware(thunk)
);

and you will be able to use thunks with your redux actions.

Refer to https://github.com/gaearon/redux-thunk#installation