Skip to main content

16.06 Action Creators And Async Code

actions.js

actions.js
export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";
export const ADD = "ADD";
export const SUBTRACT = "SUBTRACT";
export const STORE_RESULT = "STORE_RESULT";
export const DELETE_RESULT = "DELETE_RESULT";

export const increment = () => {
return {
type: INCREMENT,
};
};

export const decrement = () => {
return {
type: DECREMENT,
};
};

export const add = (value) => {
return {
type: ADD,
value: value,
};
};

export const subtract = (value) => {
return {
type: SUBTRACT,
value: value,
};
};

export const storeResult = (res) => {
return {
type: STORE_RESULT,
result: res,
};
};

export const deleteResult = (resElId) => {
return {
type: DELETE_RESULT,
resultElId: resElId,
};
};

Counter.js

Counter.js
import React, { Component } from "react";
import { connect } from "react-redux";
import CounterControl from "../../components/CounterControl/CounterControl";
import CounterOutput from "../../components/CounterOutput/CounterOutput";
import * as actionCreators from "../../store/actions/actions";

class Counter extends Component {
render() {
return (
<div>
<CounterOutput value={this.props.ctr} />
<CounterControl
label="Increment"
clicked={this.props.onIncrementCounter}
/>
<CounterControl
label="Decrement"
clicked={this.props.onDecrementCounter}
/>
<CounterControl label="Add 5" clicked={this.props.onAddCounter} />
<CounterControl
label="Subtract 5"
clicked={this.props.onSubtractCounter}
/>
<hr />
<button onClick={() => this.props.onStoreResult(this.props.ctr)}>
Store Result
</button>
<ul>
{this.props.storedResults.map((strResult) => (
<li
key={strResult.id}
onClick={() => this.props.onDeleteResult(strResult.id)}
>
{strResult.value}
</li>
))}
</ul>
</div>
);
}
}

const mapStateToProps = (state) => {
return {
ctr: state.ctr.counter,
storedResults: state.res.results,
};
};

const mapDispatchToProps = (dispatch) => {
return {
onIncrementCounter: () => dispatch(actionCreators.increment()),
onDecrementCounter: () => dispatch(actionCreators.decrement()),
onAddCounter: () => dispatch(actionCreators.add(5)),
onSubtractCounter: () => dispatch(actionCreators.subtract(5)),
onStoreResult: (result) => dispatch(actionCreators.storeResult(result)),
onDeleteResult: (id) => dispatch(actionCreators.deleteResult(id)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Counter);