I've identified 2 patterns for getting state in an action creator and am wondering which is better:
- Use redux-thunk and getState
- mapStateToProps in the component and pass the state back to Redux when calling an action creator
Example of each:
class SomeComponent {
render() {
return (
<Button onPress={this.props.networkCall}/>
)
}
}
const mapDispatchToProps = {
networkCall: actions.networkCall,
}
export default connect(undefined, mapDispatchToProps)(SomeComponent)
export networkCall() {
return (dispatch, getState) => {
const { dataForNetworkCall } = getState().someReducer
dispatch(pending())
axios.get(`something/${dataForNetworkCall}/something2`)
.then(() => {
dispatch(success())
}
...
}
}
OR
class SomeComponent {
render() {
const { networkCall, dataForNetworkCall } = this.props
return (
<Button onPress={networkCall(dataForNetworkCall)}/>
)
}
}
function mapStateToProps(state) {
const { dataForNetworkCall } = state.someReducer
return { dataForNetworkCall }
}
const mapDispatchToProps = {
networkCall: actions.networkCall,
}
export default connect(mapStateToProps, mapDispatchToProps)(SomeComponent)
export networkCall(dataForNetworkCall) {
return (dispatch) => {
dispatch(pending())
axios.get(`something/${dataForNetworkCall}/something2`)
.then(() => {
dispatch(success())
}
...
}
}
I feel like 2 is a bad idea because it involves passing state to the Component just to pass it back to Redux. However, there seems to be a lot of articles online saying option 1 is an anti-pattern (including Dan Abramov himself saying it is an anti-pattern). So, what is the "best" way?