I'm doing a simple project with React and Redux to train and I get an attribute (string) that is in the store through a function of the component I make a processing in that string and I command for action that it should send to reducer and save it in an attribute of the store. But this string comes up to action but does not go into reduer, what could be wrong? Codes below.
Component:
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { msgChanged, resultChanged, clear } from '../actions/messageAction';
import Button from './button';
class Message extends Component {
constructor(props) {
super(props);
this.encrypt = this.encrypt.bind(this);
this.decrypt = this.decrypt.bind(this);
}
encrypt() {
let step = this.props.counter.step;
let msg = this.props.message.msg.toUpperCase();
let alpha = this.props.message.alpha;
let resultAux = '';
for(let j = 0; j < msg.length; j++) {
if(msg[j] === ' ') {
resultAux += ' ';
} else {
for (let i = 0; i < alpha.length; i++) {
if(msg[j] === alpha[i]) {
let num = (i + step) % alpha.length
resultAux += alpha[num];
}
}
}
}
resultChanged(resultAux);
}
decrypt() {
let step = this.props.counter.step;
let msg = this.props.message.msg.toUpperCase();
let alpha = this.props.message.alpha;
let resultAux = '';
for(let j = 0; j < msg.length; j++) {
if(msg[j] === ' ') {
resultAux += ' ';
} else {
for (let i = 0; i < alpha.length; i++) {
if(msg[j] === alpha[i]) {
let num = (i - step) % alpha.length
resultAux += alpha[num];
}
}
}
}
resultChanged(resultAux);
}
render() {
return (
<div>
<input onChange={this.props.msgChanged} type='text' value={this.props.message.msg} />
<Button action={this.encrypt} label='Criptografar' />
<Button action={this.decrypt} label='Descriptografar' />
<Button action={this.props.clear} label='Apagar' />
<p>{this.props.message.result}</p>
</div>
)
}
};
const mapStateToProps = state => ({ message: state.message, counter: state.counter });
const mapDispatchToProps = dispatch => bindActionCreators({ msgChanged, resultChanged, clear }, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(Message);
Action:
export const resultChanged = function(resultMsg) {
console.log('action', resultMsg);
return {
type: 'RESULT_CHANGED',
payload: resultMsg
}
}
Reducer:
const INITIAL_STATE = {
msg: '',
result: '',
alpha: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
}
export default (state = INITIAL_STATE, action) => {
console.log(action.type, action.payload);
switch(action.type) {
case 'MSG_CHANGED':
return { ...state, msg: action.payload };
break;
case 'RESULT_CHANGED':
console.log('reducer', action.payload)
return { ...state, result: action.payload };
break;
case 'CLEAR':
return { ...state, msg: '' };
break;
default:
return state;
}
}