I'm learning how to use Redux and am having an issue setting up the actions and reducers. Here is my setup:
Actions are here:
export const loginUser = (test) => {
return {
type:'loginUser',
loggedIn:true
}
}
export const toggleRegLog = (test) => {
return {
type:'toggleRegLog',
}
}
Reducers are here:
let initialState = [];
const userAuthReducer = (state = initialState,action) => {
switch (action.type) {
case 'loginUser':
let newState = [...state];
if(action.loggedIn) {
newState = "logged-in";
} else {
newState = "not-logged-in";
}
return newState;
break;
case:'toggleRegLog':
let newState = [...state];
return action.state;
break;
default:
return state;
}
}
export default userAuthReducer;
Combination of reducers is here in a file called index:
import {combineReducers} from 'redux';
import userAuthReducer from './reducers/userAuthReducer';
function lastAction(state = null, action) {
return action;
}
export default combineReducers({
userAuthReducer
});
Demo component:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import { bindActionCreators } from 'redux';
import * as authActions from './actions/userAuthActions';
class App extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log(this.props)
}
render() {
return (
<div>
<button onClick={this.props.loginUser()}></button>
</div>
);
}
const mapStateToProps = (state) => {
return {
userAuthReducer:state.userAuthReducer
};
};
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(authActions,dispatch);
};
export default connect(mapStateToProps,mapDispatchToProps)(App);
}
I had the state working before in a more basic way but after looking at some more tutorials and deciding to introduce separate action creators (ie not just dispatching from my component straight to the reducer) and by introducing multiple cases in my reducer it doesn't seem to work anymore. The console.log(this.props) on my component returns the actions as functions and states as undefined.
Can anyone spot where i've gone wrong?