Redux-Form will not submit if more than one Field - redux-form

Why does my redux-form not submit when I have more than one field?
If I have more than one field then the onSubmit on my form does not run.
The following code will not show the alert :
//#flow
import * as React from 'react';
import {Field, reduxForm, Form} from 'redux-form';
class CustomerPage2 extends React.Component {
constructor(props) {
super(props);
}
render() {
let submit = () => alert("show me the money")
return (
<Form id="myform" onSubmit={submit} >
<Field
label={'asdf'}
className={'input'}
id='1'
name={'salutation'}
mandatory={true}
component='input'
/>
<Field
label={'asdf2'}
className={'input'}
id='2'
name={'first_name'}
mandatory={true}
component='input'
/>
</Form>
);
}
}
export default reduxForm({
form: 'customerRegistration',
})(CustomerPage2)
However if I remove one of the fields the alert will pop up :
render() {
let submit = () => alert("show me the money")
return (
<Form id="myform" onSubmit={submit} >
<Field
label={'asdf'}
className={'input'}
id='1'
name={'salutation'}
mandatory={true}
component='input'
/>
</Form>
);
}
I also created a fiddle where you can see it for your own eyes :
https://jsfiddle.net/036ur33k/150/
Just remove one of the fields and you will see what I mean.

I think you forgot to use the handleSubmit function (redux-form adds it on the component props) in your onSubmit event.
I modified your fiddle, check if it is what you need.
https://jsfiddle.net/036ur33k/173/

Related

React formik form onsubmit event callings many times?

import { Formik, Form, Field } from "formik";
import { Button } from "antd";
const AddUser = () => {
const initialValues = {
name: "",
};
return (
<>
<Formik
initialValues={initialValues}
onSubmit=(values) => {
alert("hi");//calling mamy times
Here added api call (post method)
}}
>
{({ isValid, submitForm, isSubmitting, values }) => {
return (
<Form>
<Field
name="name"
label="Name"
placeholder="Dataset Name"
/>
<Button
type="primar"
htmltype="submit"
loading=(props.addingdata) // this is my reducer state intial was false after post call request became true and success state value false
>
Add Dataset
</Button>
</Form>
);
}}
</Formik>
</div>
</>
);
};
export default AddUser;
I have simple formik form antd button I have used when click submit button post api calling twice and thrice even If I added loading property in button why its happening like this?

React ajax call when button onClick event using hooks

import React, { useState, useEffect } from "react";
import axios from "axios";
function App() {
const [contact, setContact] = useState({
fName: "",
lName: "",
email: ""
});
function handleClick() {
const res = axios.get("url");
}
useEffect(()=>{
handleClick();
})
return (
<div className="container">
<h1>
Hello {contact.fName} {contact.lName}
</h1>
<p>{contact.email}</p>
<input name="fName" placeholder={contact.fName} />
<input name="lName" placeholder={contact.lName} />
<input name="email" placeholder={contact.email} />
<button onClick={handleClick}>Submit</button>
</div>
);
}
export default App;
I set initial state with empty string but I am trying to update input attributes with data from external source whenever user clicks submit button.
I heard I need to use useEffect method to api call in react, but I have no idea where to start.
if you're going to update the data on the button click, then you can use a count mechanism, a separate variable to keep track of the count.
const [count, setCount] = useState(0);
<button onClick={() => setCount(count + 1 )}>Submit</button>
async function handleClick() {
const res = await axios.get("url");
setContact(res.data);
}
useEffect(() => {
handleClick();
}, [contact, count]);

React-Redux how to use reusable checkbox component for displaying data

I have been asked to tamper with React-Redux code (knowing very little at the moment) and update a colleague's front-end code. One of the application's functionality, is for the administrator to create alert notifications and distribute them across different departments. These departments are selected with checkboxes and finally with a 'Send' button, they alert everyone involved. The form with all the necessary fields, is saved in the database. The notification details page, has detailed information and the mockup that we are supposed to produce, has the involved departments with the same form of grouped checkeboxes (along with their checked/unchecked status).
My colleague had created a reusable component like so:
import React from "react";
import { connect } from "react-redux";
import {reset, change, registerField } from "redux-form";
import _ from "lodash";
import DepartmentTypeCheckBoxes from "./ThreatTypeCheckBoxes";
import { setNotifView, setNotifViewForm } from "Actions/notifView.action";
import { Label } from "reactstrap";
import { ICustomProps } from "Entities/baseForm";
interface INotificationState {
notifStatus?: boolean;
}
interface IProps extends ICustomProps {
registerField(): void;
resetForm(): void;
changeField(value: any): any;
setNotifView(view: any): void;
setNotifViewForm(form: any): void;
}
class DepartmentType extends React.Component<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
};
this.onFieldChange = this.onFieldChange.bind(this);
}
public componentWillMount() {
this.props.registerField();
}
public onFieldChange() {
if(this.state.status && this.state.status == true){
this.setState({ status: false })
this.props.changeField(false);
}
else{
this.setState({ status: true })
this.props.changeField(true);
}
}
public componentWillReceiveProps(nextProps: IProps , nextState: IState) {
}
public render() {
return (
<div className="form-group">
<div className="f" >
<Label for="type">Department Types</Label>
<div className="">
<div className="">
<DepartmentTypeCheckBoxes id="1" value="option1" label="Development" fieldName="development" formName="CreateAlertNotification"></DepartmentTypeCheckBoxes>
</div>
<div className="">
<DepartmentTypeCheckBoxes id="2" value="option2" label="Human resources" fieldName="humanResources" formName="CreateAlertNotification"></DepartmentTypeCheckBoxes>
</div>
<div className="">
<DepartmentTypeCheckBoxes id="3" value="option3" label="Consultance" fieldTag="consultance" formTag="CreateAlertNotification"></DepartmentTypeCheckBoxes>
</div>
</div>
<div className="">
<div className="">
<div className="">
<DepartmentTypeCheckBoxes id="4" value="option4" label="Logistics" fieldTag="logistics" formTag="CreateAlertNotification"></DepartmentTypeCheckBoxes>
</div>
</div>
<div className="">
{this.props.children && this.props.children}
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state: any, ownProps: ICustomProps) => {
return {
};
};
const mapDispatchToProps = (dispatch: any, ownProps: ICustomProps) => {
const formTag = ownProps.formTag;
const fieldTag = ownProps.fieldTag;
return {
registerField: () => dispatch(registerField(formTag, fieldTag, "FieldArray")),
changeField: (value: any) => dispatch(change(formTag, fieldTag, value, false, false)),
setNotifView: (view: any) => dispatch(setNotifView(view)),
setNotifViewForm: (form: any) => dispatch(setNotifViewForm(form)),
resetFields: () => dispatch(reset("CreateAlertNotification")),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(DepartmentType);
and uses it in the submission form like so:
<Row>
<Col md="6">
{ initialValues.ShowDepartmentBoxes &&
<DepartmentType fieldTag="DepType" formTag="CreateAlertNotification">
<Field name="AnotherCustomField" className="form-control" component={renderField} type="text" label="General Information" />
</DepartmentType>
}
</Col>
<Col md="6">
<AnotherCustomField fieldTag="SomeFieldName" formTag="CreateAlertNotification" Mode="create"/>
</Col>
</Row>
I want to use the same DepartmentType field in my "Notification Details" page, with the values loaded in the notification object from the db. Assuming I have 4 bool values like
notification.IsHumanResourcesAlerted
notification.IsDevelopmentAlerted,
notification.IsLogisticsAlerted,
notification.IsConsultanceAlerted
how will I pass them in the details page that is NOT a form and the "value" in the DepartmentTypeCheckBoxes seems to be predefined?
I have not found anything relevant yet and because we are on a tight schedule, I want to try and come up with a solution as possible.
Any help is appreciated.
I might be misunderstanding the implementation of your form and your details page, but if you need the form to exist exactly as it is selected on your send page you could see how the values of this form are being dispatched. With that information you could build something into an existing reducer for your details page or create a new reducer that holds those values and then use them later on to display your details page.
This would most likely be considered improper usage of Redux store (see https://goshakkk.name/should-i-put-form-state-into-redux/ for why I feel that may be the case). But it would work for your implementation as I understand it.
Edit: I should also mention that to display this data you could just display it as the same form as before, but disable the checkboxes so that the preselected values you imported cannot be changed.

Form-level validation does not behave as expected

Using redux-form 7.0.3, I'm unable to get the Field validate API to do anything.
First, I created a basic, minimal example templated off of the docs.
import React from 'react'
import { Field, reduxForm } from 'redux-form'
// removed validation fns
const required = value => {
console.log('Test of validation fn')
return (value ? undefined : 'Required')
}
// unchanged
const renderField = ({
input,
label,
type,
meta: { touched, error, warning }
}) =>
<div>
<label>
{label}
</label>
<div>
<input {...input} placeholder={label} type={type} />
{touched &&
((error &&
<span>
{error}
</span>) ||
(warning &&
<span>
{warning}
</span>))}
</div>
</div>
// removed fields & made into React Component
class FieldLevelValidations extends Component {
render(){
const { handleSubmit } = this.props
return (
<form onSubmit={handleSubmit}>
<Field
name="test"
type="text"
component={renderField}
label="Test Component"
validate={required}
/>
<div>
<button type="submit">
Submit
</button>
</div>
</form>
)
}
}
export default reduxForm({
form: 'fieldLevelValidation'
})(FieldLevelValidations)
From this I would assume that the forms reducer processes an action that sets a prop that can be accessed in renderField, but it does not. Both error and warning are undefined, and required is never called. Additionally, there is no isValid or the like property set in the store. I don't know if this is a bug or if I'm missing some critical piece, but I would expect more to be happening here. Also, some greater detail in the docs would be nice.

How to hijack submit to add values?

I have a form that can have different state based on which button was used for submission; one does a simple submit while the other one adds a flag then submit.
I found a working solution that is, imo, quite ugly, so I'd like to know how else to do it ?
class MyForm extends Component {
// Hijack submit to add published flag
handlePublish = (e) => {
e.preventDefault();
const { handleSubmit, onSubmit } = this.props;
handleSubmit((values) => {
onSubmit({
...values,
isPublished: true,
});
})();
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit}>
<Field
name="foo"
component="input"
/>
<button
type="submit"
onClick={this.handlePublish}
>
Publish
</button>
<button type="submit">
Save
</button>
</form>
);
}
}
✅ This is the idiomatic way. Alternatively, you could provide any number of values as initialValues that don't actually have a Field on the form, but will be submitted.

Resources