https://codesandbox.io/s/jvj6o043yv
I'm trying to grok the basics of react-redux connect, Provider, and mapStateToProps and MapDispatchToProps using the very simple Counter example. The point of the exercise is to have the props and actions injected into the Counter component.
The issue I'm seeing is that my actions are firing twice on each button click. I'm a Redux noob so I'm sure (I hope) it's a fairly basic error. I'd appreciate any pointers to where I went wrong. Thanks in advance.
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { connect } from 'react-redux'
import { createStore, applyMiddleware } from 'redux';
import { createLogger } from 'redux-logger';
// Reducer
const counter = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
// store setup
const configureStore = () => {
const middlewares = [];
if (process.env.NODE_ENV !== 'production') {
middlewares.push(createLogger());
}
return createStore(
counter,
applyMiddleware(...middlewares)
);
};
const store = configureStore();
// functional component
let Counter = ({
currCounter,
onIncrement,
onDecrement
}) => (
<div>
<h1>{currCounter}</h1>
<button onClick={onIncrement}>+</button>
<button onClick={onDecrement}>-</button>
</div>
);
// Connect logic
const mapStateToProps = (state) => ({
currCounter: state
})
const mapDispatchToProps = {
onIncrement: () =>
store.dispatch({
type: 'INCREMENT'
}),
onDecrement: () =>
store.dispatch({
type: 'DECREMENT'
}),
}
Counter = connect(
mapStateToProps,
mapDispatchToProps
)(Counter)
// Entry point
const render = () => {
ReactDOM.render(
<Provider store={store}>
<Counter />
</Provider>,
document.getElementById('root')
);
};
store.subscribe(render);
render();