Accessing "getstate" From Within Action Creator Using Redux-thunk?
I have a mapDispatchToProps function like this one below. export function mapDispatchToProps(dispatch, ownProps) { return { handleChangeLang: changeLocaleDispatcher(dispatch)
Solution 1:
Your initial syntax is wrong, and the "hacky" example is also not how you should go about it.
A sample would look like:
import {thunkAction1, thunkAction2} from"myActions";
import {bindActionCreators} from"redux";
constmapDispatchToProps(dispatch) => {
return {
manuallyBoundAction : (...args) =>dispatch(thunkAction1(...args)),
autoBoundAction : bindActionCreators(thunkAction2, dispatch),
multipleActionsTogether : bindActionCreators({thunkAction1, thunkAction2}, dispatch)
}
};
And no, getState
itself is not accessible inside mapDispatchToProps
. It's available inside the thunk, but not mapDispatch
.
You may want to read this answer on why thunks exist, as well as the Redux docs on async actions.
Solution 2:
So while I don't see your current action creator in your question, I will assume it's ES6/ES2015 javascript.
The below should give you freedom to grab any state. Since you have redux-thunk
, you should be good to go.
exportfunctionsetActivity(activityName) {
returnfunction (dispatch, getState) {
dispatch({
type: SET_ACTIVITY,
description: 'Set the name of the activity being done now',
currentActivityName: activityName,
currentActivityData: getState().activityStore.activities[activityName]
});
};
}
activityStore is same as what you've defined for that particular reducer, see below.
exportconst reducers = {
activityStore: ActivityStore.reducer,
someOtherStore: SomeOtherStore.reducer
};
Solution 3:
Hacky fix :/
letProvidedApp = (serverProps) => {
let store = getStore(serverProps)
letConnectedApp = connect(
mapStateToProps,
mapDispatchToProps(store)
)(App)
return (
<Providerstore={store}><ConnectedApp/></Provider>
)
}
exportfunctionmapDispatchToProps(store) {
return(dispatch, ownProps) => {
return {
handleChangeLang: store.dispatch(changeLocaleDispatcher),
handleChange: store.dispatch(handleChangeDispatcher),
handleSubmit: store.dispatch(handleSubmitDispatcher)
}
}
}
Post a Comment for "Accessing "getstate" From Within Action Creator Using Redux-thunk?"