I'm having difficulty in updating state with a React/Redux setup while trying to update the state of muliple input fields in a form. I'm getting the state updated, but there is an index for every keyup.
How can I update the state to only include the updated items in state?
expected
userGenerated:
Array(4)
0:{yourName: "fg"}
1:{yourStory: "gd"}
actual
userGenerated:
Array(4)
0:{yourName: "f"}
1:{yourName: "fg"}
2:{yourStory: "g"}
3:{yourStory: "gd"}
reducer
export default function(state = [], action) {
switch (action.type) {
case "USER_GEN_INPUT":
let { input, name } = action.payload;
let newState = state;
let userGenerated = {
[name]: input
};
return [...newState, userGenerated];
default:
return state;
}
}
action
export function handleUserGenInput(input, name) {
return {
type: actions.USER_GEN_INPUT,
payload: {
input,
name
}
};
}
component
import React, { Component } from "react";
import { connect } from "react-redux";
import { handleUserGenInput } from "../actions";
/**
* Form to handle User Generated Content
* And post to the back end of WP - CRV
*/
class UserGenerated extends Component {
constructor(props) {
super(props);
this.onHandleChange = this.onHandleChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
// Handle submitting the form to the backend
onSubmit(e) {
e.preventDefault();
console.log(this.props);
}
// Dispatch the action to the Redux store whenever a change event happens
onHandleChange(e) {
/**
* @param value of input field
* @param name of input field
*/
this.props.handleUserGenInput(e.target.value, e.target.name);
}
render() {
return (
<section>
<form onSubmit={this.onSubmit}>
<input
type="text"
value={this.props.value}
name="yourName"
onChange={this.onHandleChange}
/>
<textarea name="yourStory" onChange={this.onHandleChange} />
<button>Submit</button>
</form>
</section>
);
}
}
function mapStateToProps(state) {
return { userGenerated: state.userGenerated };
}
const mapDispatchToProps = {
handleUserGenInput
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserGenerated);