Amount updates in redux store but not in component state .what wrong i am doing?
Amount is 0 in component state
Component
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux';
class testComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'shirt',
quantity: 2,
rate: 4,
amount: 0,
}
}
computeAmount() {
this.props.dispatch({
type: 'COMPUTE_AMOUNT',
paylod: { rate: this.state.rate, quantity: this.state.quantity }
})
}
render() {
return (
<div>
AMOUNT IN REDUX = {this.props.amount}
<div>
<input value={this.state.name} />
quantity <input value={this.state.quantity} />
rate <input value={this.state.rate} />
amount <input value={this.state.amount} />
</div>
AMOUNT IN STATE = {this.state.amount}
<div> <button onClick={(e) => this.computeAmount(e)} >Compute Amount</button> </div>
</div>
);
}
}
testComponent.propTypes = {
dispatch: PropTypes.func.isRequired,
amount: PropTypes.number.isRequired
}
const mapStateToProps = (state) => {
return {
amount: state.rootReducer.testReducer.amount
}
}
export default connect(mapStateToProps)(testComponent)
Reducer
import update from 'immutability-helper';
let initialState = {amount : 0}
const testReducer = (state = initialState, action) => {
switch (action.type) {
case 'COMPUTE_AMOUNT':
action.paylod.amount = action.paylod.rate * action.paylod.quantity
//Try 1
return { ...state, ...action.paylod }
//Try 2
// return update(state, { $set: action.paylod });
//Try 3
//return update(state, { $merge: action.paylod });
default:
return state;
}
}
export default testReducer;
Thanks @Mohamed Binothman

