Reputation: 577
I've got a React app connected to Redux.
I've got an action creator which I use to fetch setup data.
Right at the top of my stateful component, I import it as such:
import { fetchSetup } from "../../store/actionCreators";
This is the actual fetchSetup() function:
export const fetchSetup = (clientID = 1) => async dispatch => {
const clientIDObj = {
user_id: clientID
};
await fetch(`${apiURLs.setup}`, {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(clientIDObj)
})
.then(response => {
return response.json();
})
.then(json => {
console.log("fetchSetup()", json);
dispatch({ type: actionTypes.FETCH_SETUP, payload: json });
});
};
When I connect it to the Redux store as below, everything works great:
export default connect(
mapStateToProps,
{ fetchSetup }
)(withRouter(Landing));
However, this is code cobbled together from various tutorials and such. I'm trying to connect another function in the way that I normally do it.
const mapDispatchToProps = dispatch => {
return {
onUnauthenticated: () => dispatch({ type: actionTypes.UNAUTHENTICATED }),
fetchSetupData: fetchSetup()
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(withRouter(Landing));
Although there are no errors, it simply never seems to actually execute my action creator. I never see any action dispatched in my Redux dev tools and I don't see any console.logs from inside the action creator function.
How can I connect my action creator in such a way that I can also connect other functions and they all work?
Upvotes: 0
Views: 118
Reputation: 281626
There are multiple ways to use mapDispatchToProps
. The one way which works for you is the method of providing object
as mapDispatchToProps which redux internally then dispatches.
The second way which doens't work for you needs to have a function which is dispatched and not just called
const mapDispatchToProps = dispatch => {
return {
onUnauthenticated: () => dispatch({ type: actionTypes.UNAUTHENTICATED }),
fetchSetupData: () => dispatch(fetchSetup())
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(withRouter(Landing));
Upvotes: 1