I am learning how to use Redux, and I have a problem setting up actions and reducers. Here is my setup:
Actions here:
export const loginUser = (test) => {
return {
type:'loginUser',
loggedIn:true
}
}
export const toggleRegLog = (test) => {
return {
type:'toggleRegLog',
}
}
Gearboxes 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;
The combination of gears is here in the file with the 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 a condition that worked earlier in a simpler way, but after looking at a few more manuals and deciding to introduce individual action creators (i.e. not just send from my component directly to the gearbox) and entering a few cases in my gearbox seems to be more does not work. console.log(this.props)
on my component returns actions as functions and states as undefined.
Can anyone see where I made a mistake?
source
share