I am trying out React/Redux/JS for the first time. I am a little confused about setting state in component vs letting redux update it.
I want to click a button to set the lightOn to true and have the updated this.props.lightOn value display. I am missing something fundamental but not sure what.
action:
export const setLight = lightStatus => dispatch => {
const res = lightStatus;
console.log(res); // => true on click
dispatch({ type: SET_LIGHT, payload: res });
};
In the component, {this.props.onLight} is undefined so I am not updating state correctly:
import React, { Component } from 'react';
import { connect } from 'react-redux';
//import * as actions from '../actions';
import { setLight } from '../actions';
import { bindActionCreators } from 'redux';
class Light extends Component {
render() {
return (
<div>
Light Status: {this.props.lightOn}
<button
className="btn"
onClick={() => this.props.setLight(true)}
>
Set Light!
</button>
</div>
);
}
}
function mapStateToProps(state) {
return {
lightOn: state.lightOn
};
}
function mapDispatchToProps(dispatch) {
//whenever selectBook is called the result should be passed to all of our reducers
return bindActionCreators({ setLight: setLight }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Light);
the reducer (updated with spread operator):
import { SET_LIGHT } from '../actions/types';
export default function(state = [], action) {
switch (action.type) {
case SET_LIGHT:
return { ...state, lightOn: action.payload };
default:
return state;
}
}