Reputation: 97
I have 3 actions I am trying to use in this component. One logs me out of Firebase Google Auth (working correctly), and the other two are simply changing a piece of state to a certain string which I am going to use later to determine what component to render.
The commented out mapDispatchToProps works fine and it's how I'm used to writing it, the one using the logout method is the syntax I can't figure out. How can I refactor the below so that setRoutines and setExercises work?
The component:
import React from 'react';
import { connect } from "react-redux";
import { firebaseLogout } from '../Auth/Auth.actions';
import { setRoutines, setExercises } from './Profile.actions';
const Profile = ({logout, setRoutines, setExercises}) => (
<React.Fragment>
<button onClick={setRoutines}>My Routines</button>
<button onClick={setExercises}>My Exercises</button>
<button onClick={logout}>Logout</button>
</React.Fragment>
);
const mapDispatchToProps = (dispatch) => ({
logout: () => dispatch(firebaseLogout()),
setRoutines,
setExercises,
});
// const mapDispatchToProps = {
// setRoutines,
// setExercises
// };
export default connect(
undefined,
mapDispatchToProps
)(Profile);
My actions file:
export const setRoutines = () => ({
type: "SET_ROUTINES",
payload: "routines"
});
export const setExercises = () => ({
type: "SET_EXERCISES",
payload: "exercises"
});
export const logout = () => ({
type: 'LOGOUT'
});
export const firebaseLogout = () => {
return () => {
return firebase.auth().signOut();
}
};
My reducer file:
export default (state = {view:'routines'}, action) => {
switch (action.type) {
case 'SET_ROUTINES':
return {
...state,
view: action.payload
};
case 'SET_EXERCISES':
return {
...state,
view: action.payload
};
case 'LOGOUT':
return {};
default:
return state;
}
};
Upvotes: 2
Views: 6091
Reputation: 101
By modifying the mapDispatchToProps
to the below mention format should help in creating a bound action creator that automatically dispatches.
const mapDispatchToProps = (dispatch) => ({
logout: () => dispatch(firebaseLogout()),
boundRoutines: () => dispatch(setRoutines()),
boundExercises: () => dispatch(setExercises()),
});
After creating a bound action creator we can call the creator as follows.
const Profile = ({logout, boundRoutines, boundExercises}) => (
<React.Fragment>
<button onClick={boundRoutines}>My Routines</button>
<button onClick={boundExercises}>My Exercises</button>
<button onClick={logout}>Logout</button>
</React.Fragment>
);
Upvotes: 5