I have setup React-Redux form, but upon submit I am getting an empty object in the console.log()
Here is my code
import React from 'react';
import {reduxForm} from 'redux-form';
import {stockSave} from '../actions/actions';
class Stock extends React.Component {
customHandler(values){
console.log(values);
//this.props.stockSave(values);
}
render() {
const {fields: {id}, handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.customHandler)}>
<input type="text" {...id} />
<button type="submit">Submit</button>
</form>
)
}
};
export default reduxForm({
form: 'myForm',
fields: ['id']
}, null, {stockSave})(Stock);
After submitting the form, I get empty object in the console. Here is the screenshot https://www.screencast.com/t/lzNoKPwsLU
Any help regarding this problem? Thanks!
You need to add a constructor in your class and bind your customHandler function.
class Stock extends React.Component {
constructor(props) {
super(props);
this.customHandler = this.customHandler.bind(this);
}
customHandler(values){
console.log(values);
//this.props.stockSave(values);
}
render() {
const {fields: {id}, handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.customHandler)}>
<input type="text" {...id} />
<button type="submit">Submit</button>
</form>
)
}
};
export default reduxForm({
form: 'myForm',
fields: ['id']
}, null, {stockSave})(Stock);
And why are calling handleSubmit from pros and passing your customHandle as parameter?
I think that you want to call your handleSubmit this would be better:
customHandler(values){
this.props.handleSubmit();
console.log(values);
//this.props.stockSave(values);
}
Related
I am trying to display input value on submit. But it seems to be not working. I don't have any errors but nothing being rendered. What is wrong with the code?
import React from 'react';
import { Component } from 'react';
class App extends Component {
constructor (props) {
super(props)
this.state = {
city : ""
}
}
handleSubmit = (event)=> {
event.preventDefault();
this.setState ({
city : event.target.value
})
}
render () {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input type = "text" city = "city_name" />
<button type="submit">Get Weather</button>
{this.state.city}
</form>
</div>
)
}
}
export default App;
<form
onSubmit={e=>{
e.preventDefault()
console.log(e.target[0].value)
}}>
<input type="text"/>
<button type="submit">dg</button>
</form>
that works for me very well
Remember onSubmit target:
Indicates where to display the response after submitting the form. So you can get inner elements (and their corresponding values) like normal javascript code.
const city = event.target.querySelector('input').value
handleSubmit = (event) => {
event.preventDefault();
this.setState ({ city })
}
I guess you want it to get work like below. But this is not the only way to get it done.
import React from "react";
import { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
city: ""
};
}
handleSubmit = (event) => {
const formData = new FormData(event.currentTarget);
event.preventDefault();
let formDataJson = {};
for (let [key, value] of formData.entries()) {
formDataJson[key] = value;
}
this.setState(formDataJson);
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input type="text" name="city" />
<button type="submit">Get Weather</button>
{this.state.city}
</form>
</div>
);
}
}
export default App;
Code sandbox => https://codesandbox.io/s/eager-oskar-dbhhu?file=/src/App.js
I basically making a todolist app.I just want the user entered text and add it to my state.But when i click the button the state is not getting updated with the new todoItem.please help with this.
My state is in Context.js
import React from 'react';
const Context=React.createContext();
const reducer=(state,action)=>{
switch(action.type){
case "ADD_TODO":
return {
...state,
todos:[action.payload,...state.todos]
}
default:
return state;
}
}
export class Provider extends React.Component{
state={
todos:[
{id:"1",todoItem:"Code daily"},
{id:"2",todoItem:"play"},
{id: '16a1c935-a033-4272-85b4-4412de42b59f', todoItem: 'wdwdwd'},
],
dispatch:action=>{
this.setState(state=>{
reducer(state,action)
})
}
}
render(){
return(
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
)
}
}
export const Consumer=Context.Consumer;
My Input Component for taking the todoitem input from user and add it to the state.But my page is reloading but my user entered text is not added to the state.And there is no error showing.
InputTodo.js
import React, { Component } from 'react';
import '../css/InputTodo.css';
import { v4 as uuidv4 } from 'uuid';
import {Consumer} from '../context';
class InputTodo extends Component {
constructor(props){
super(props);
this.state={
inputValue:""
};
}
OnChange(event){
const txtEntered=event.target.value;
this.setState({
inputValue:txtEntered,
});
}
handleButtonClicked=(dispatch,event)=> {
event.preventDefault();
const inputValue=this.state.inputValue;
const newTodo={
id:uuidv4(),
todoItem:inputValue,
}
dispatch({type:'ADD_TODO',payload:newTodo});
this.setState({
inputValue:"",
});
this.props.history.push('/');
}
render() {
return(
<Consumer>
{value=>{
const {dispatch}=value;
return (
<form onSubmit={this.handleButtonClicked.bind(this,dispatch)}>
<div className="form-group">
<input value={this.state.inputValue} onChange={this.OnChange.bind(this)} className="form-control" placeholder="Enter the todo" />
<button type="submit" className="btn btn-primary">Add</button>
</div>
</form>
)}}
</Consumer>
)
}
}
export default InputTodo;
You just forgot to return the new state in dispatch setState:
export class Provider extends React.Component{
state={
/* ... */
dispatch:action=>{
this.setState(state=>{
return reducer(state,action) /* <--- Here you missed the return */
})
}
}
/* ... */
I'm trying to add to redux-form field of type Editor from react-draft-wyswig. As I read from redux-form docs I need to connect it by value and onChange properties in Field component (from redux-form).
I built a component with additional property value which stores a html code of current wyswig-editor:
class WYSWIGField extends Component {
constructor(props) {
super(props);
this.state = { editorState: EditorState.createEmpty(), value: '' };
this.onChange = this.onChange.bind(this);
}
onChange(editorState){
this.setState({ editorState: editorState,
value: draftToHtml(convertToRaw(editorState.getCurrentContent()))});
//console.log(this.state.value);
};
render() {
return (
<div>
<Editor
editorState={this.state.editorState}
onEditorStateChange={this.onChange}
/>
</div>
);
}
}
My form:
<form onSubmit={handleSubmit(this.props.addPost)}>
<Field name="editor" component={WYSWIGField}/>
<button type="submit">Add post</button>
</form>
Export:
export default connect(null, { addPost })(
reduxForm({form: "AddPostForm"})(Posts));
And action creatow where I always receive empty object without my values from editor:
export function addPost(prop) {
console.log("prop", prop);
return{
type: ADD_POST,
payload: prop
};
}
Could somebody help me with this? Where I did mistake?
Thank you
i am using redux forms and redux to push form values into the store/state. First thing is, i get the state as undefined in form component when i pass it as props from container(INFORMATION COMPONENT) component which is not a React component class and finally use update function to update the store. I am new to React and the redux form is throwing me off
// App Component
class App extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div className="App">
<InformationFrom state={this.props}/>
</div>
);
}
}
const mapStateToProps = (reduxState) => {
return reduxState;
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(actionCreators, dispatch);
}
export default connect(
mapStateToProps, mapDispatchToProps
)(App)
// InformationForm Component
export default class InformationFrom extends React.Component {
render() {
return (
<div>
{console.log("infoForm props >> ", this.props)}
<SimpleForm/>
</div>
)
}
}
// Form stateless function component
const SimpleForm = props => {
const { handleSubmit, pristine, reset, submitting } = props
const state = this.props.state; // is undefined
return (
<div>
{ console.log("from state here >> ", this.props) }
<form onSubmit={handleSubmit(this.updateStore(values,state))} name="InformForm">
<div>
<div>
<Field name="firstName" component={renderInput} type="text" placeholder="First Name" label={"First Name"} />
<Field name="lastName" component={renderInput} type="text" placeholder="Last Name" label={"Last Name"} />
<Field name="email" component={renderInput} type="text" placeholder="Email" label={"Email"} />
</div>
</div>
<div style={style.normal}>
<button type="submit" disabled={submitting}>
Submit
</button>
<button type="button" disabled={submitting} onClick={reset}>
Clear Values
</button>
</div>
</form>
</div>
)
}
function updateStore(values, state){
let newStore = {};
newStore = {
}
return newStore;
}
const validate = values => {
const errors = {}
if (!values.firstName) {
errors.firstName = "Required!"
}
return errors;
}
const style = {
normal: {
margin: '10px'
}
}
export default reduxForm({
form: 'simple', // a unique identifier for this form
destroyOnUnmount: false,
validate
})(SimpleForm)
You are not pass props to SimpleForm in InformationFrom, so need to update
export default class InformationFrom extends React.Component {
render() {
return (
<div>
{console.log("infoForm props >> ", this.props)}
<SimpleForm/>
</div>
)
}
}
to
<SimpleForm {...this.props} />
and Export with connect to get state from redux
export default connect((state)=>state)( reduxForm({
form: 'simple', // a unique identifier for this form
destroyOnUnmount: false,
validate
})(SimpleForm) );
I try to set my values in my redux-form, but the input doesn't show the value. Can somebody please help me?
This is my code.
import React from "react";
import { Field, reduxForm } from "redux-form";
import {connect} from 'react-redux';
import {renderTextField, renderField, validate, warn} from "../../../Components/Forms/renders"
class SyncValidationForm extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {}
}
}
render() {
const { handleSubmit, pristine, reset, submitting } = this.props;
return (
<form onSubmit={handleSubmit}>
<div className="col-sm-12">
<h4 className="info-text"> Let's start with the basic details</h4>
</div>
<Field name="what.title.value" type="text" component={renderField} label="Titel" />
</form>
);
}
}
SyncValidationForm = reduxForm({
form: 'insertstart',
enableReinitialize: true,
validate, // <--- validation function given to redux-form
warn
})(SyncValidationForm);
const mapStateToProps = state => {
return {
initialValues: state.items.item,
}
}
export default connect(mapStateToProps)(SyncValidationForm)
I my console log I see this by console.log(this.props);
initialValues:{what.title.value: "test"}
You need to pass the initial values as an object, so instead of
what.title.value: "test"
your state.items.item should look like:
{ what: { title: { value: "test" } } }
See here for a working example.
Always use change function to bind data in redux-form fields
componentWillMount() {
const { change } = this.props
change('basicDetails', 'sdfuhdsuiafghfudsauifhdsuifhuiads') // this will bind name with basicDetails
}
<form onSubmit={handleSubmit}>
<div className="col-sm-12">
<h4 className="info-text"> Let's start with the basic details</h4>
</div>
<Field name="basicDetails" type="text" component={renderField} label="Titel" />
</form>