Skip to content

Instantly share code, notes, and snippets.

@thom-nic
Created April 13, 2016 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thom-nic/fbedf27a5222a8490aa9028a40bf053c to your computer and use it in GitHub Desktop.
Save thom-nic/fbedf27a5222a8490aa9028a40bf053c to your computer and use it in GitHub Desktop.
re: "Two Weird tricks with Redux" by @jlongster
/*
* Re: http://jlongster.com/Two-Weird-Tricks-with-Redux specifically James' comment on having to wait on an action:
*
* redux-thunk returns whatever value is returned by my action. In this case I'm using axios so it already returns a promise.
* So if I want to do something after an async action completes (without having to go through the redux store that gets
* updated by some sort of ACTION_DONE state) I can just `.then()` on the promise returned by my action creator.
*
* Example follows:
*/
import 'http' from aixos;
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { replaceState } from 'redux-router';
// here's my action creator that uses redux-thunk and *returns a promise*
function deleteUser(userID) {
return dispatch =>
// this promise gets returned when the bound action creator is called:
http.delete(`/users/${userID}`)
.then(resp => dispatch({type:"USER_DELETE_SUCCESS",data:resp.data}))
}
// a component that uses the action:
export class UserDeleteButton extends React.Component {
render() {
<button onClick={ this.doDelete }>Delete!</button>
}
doDelete = (evt) => {
const { deleteAction, userID } = this.props;
// Perform navigation after async delete action has completed
deleteAction(userID).then(() => replaceState(null, '/users'))
}
}
// react-redux passes a bound action creator to the components props such that
// when called it will call the returned thunk, passing the redux dispatcher
export default connect(null, {deleteAction: deleteUser})(UserDeleteButton)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment