score:2
From your OP, you seem to have some confusion on what really happens under the hood.
I for one, would prefer to handle errors as required fields, purely with the html5 required
attribute.
It will not submit the form, until all field validations are handled.
So if you need a required text field, just use:
<input type="text" required />
This will automatically indicate that this input field needs a value (handling updating the state with the changed value is covered in the code sample below).
For the rest it seems to be all about control, do you want the parent component to handle the errors in your child control, or should the child control handle those errors? You seem to want to have both, I really wouldn't bother with sending the full state to the parent, all the parent should really care about, is what I send :)
Handling your internal state of the child component is another thing, but you are not really showing how you set your form variables at the moment. In my case, I use controlled inputs, meaning, the value they have is never undefined, and I have an onChange
eventhandler attached to them to update the child components state, which changes the input
element in the following state
<input type="text" required name="firstName" value={ this.state.firstName } onChange={ this.updateField } />
Where updateField
is defined in the following way
updateField( e ) {
// name is the name given to the input field, in the sample 'firstName'
const { name, value } = e.target;
// and I update the state as
this.setState({ [name]: value });
}
After the this.setState
has completed, a new render will start, and the firstName will get the new value that was just set to it.
At this time, when all required fields are filled out, the handleSubmit
function will be called when clicking the submit button, and I can send the data I actually want to send to my parent form, the state has the latest information, and there is no need to handle any error handling, as the browser would have taken care of that already.
const { Component } = React;
class SomeForm extends Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind( this );
this.updateField = this.updateField.bind( this );
this.state = {
firstName: '', lastName: ''
};
}
handleSubmit(e) {
const { onSubmit } = this.props;
const { firstName, lastName } = this.state;
e.preventDefault();
onSubmit({ firstName, lastName });
}
updateField( e ) {
const { target } = e;
const { name } = target;
this.setState({
[name]: target.value
});
}
render() {
const { firstName, lastName } = this.state;
return (
<form onSubmit={ this.handleSubmit }>
<div>
<span>First name:</span>
<span>
<input
type="text"
name="firstName"
value={ firstName }
required
onChange={ this.updateField } />
</span>
</div>
<div>
<span>Last name:</span>
<span>
<input
type="text"
name="lastName"
value={ lastName }
required
onChange={ this.updateField } />
</span>
</div>
<div>
<button>Submit</button>
</div>
</form>
);
}
}
class InputDataHandler extends Component {
constructor() {
super();
this.onSubmit = this.onSubmit.bind( this );
}
onSubmit( inputData ) {
console.log( inputData );
}
render() {
return (
<div>
<SomeForm onSubmit={this.onSubmit} />
</div>
);
}
}
const container = document.getElementById('container');
ReactDOM.render( <InputDataHandler />, container );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container"></div>
Clearly, you shouldn't only consider client side validation, but handle the input server side as well to ensure that your client side validation didn't get bypassed, but that's in your case a side note.
score:-1
I hope it will be useful for You: https://reactjs.org/docs/error-boundaries.html#how-about-event-handlers.
How about to wrap onFormSubmit
calling in try/catch
?
errorHandling = (error) => {
this.setState({ error });
// !this.state.origin ? this.setState({ originError: true }) : this.setState({ originError: false });
// !this.state.destination ? this.setState({ destinationError: true }) : this.setState({ destinationError: false });
// !this.state.date ? this.setState({ dateError: true }) : this.setState({ dateError: false });
// !this.state.time ? this.setState({ timeError: true }) : this.setState({ timeError: false });
}
handleSubmit = (e) => {
e.preventDefault();
try {
const { onFormSubmit } = this.props;
onFormSubmit(this.state);
} catch (error) {
this.errorHandling(error);
}
}
Also recommend to read about setState async
Source: stackoverflow.com
Related Query
- State passed to parent is updated late (after one click)
- why state is not updated after button click in setinterval react?
- Access the child state from the parent after click event from the parent
- Why state is not updated after button click using hooks?
- Updated state is not passed as props to component after setState()
- State is always one click late
- How to update state of parent component after the server is updated in child component?
- React: Child State isn't updating after Parent state gets Updated
- the marker is added after the second click state hasn't been updated with the newItem you added yet?
- Parent state passed as props not updated when rendered in .map function
- The state is not updated after click in ReactJs
- state is not updating in child component after updated inside parent component
- React Child Component Not Updating After Parent State Change
- Can we pass setState as props from one component to other and change parent state from child component in React?
- Console.log() after setState() doesn't return the updated state
- React, updating state in child component using props after async call in parent component
- react-google-maps map not updated when passed props and the marker is one location behind when updated
- How to set Select component in Material-UI to loose its focus state after selecting one of its item
- Using updated redux state right after dispatch
- Change state on click then change again after delay and show message in React
- React, can't access updated value of state variable inside function passed to setInterval() in useEffect()
- How test callback click in child component that was passed from parent component?
- Prevent child's state from reset after parent component state changes also get the values of all child components:ReactJS+ Typescript
- Child component not re-rendering even though parent state is updated using hooks
- getDerivedStateFromProps Does not re-render after Redux Reducer state is updated
- After Simulate('change') state is not updated
- React Click Counter: Updating State of just one element
- Why my state is not getting updated even after writing the setState method?
- Function passed and invoked in child component doesn't have access to parent state value
- State is not updated after dispatching an action
More Query from same tag
- How to get refresh_token in Okta using SPA or web app
- D3 Bubble chart in Reactjs has empty circles
- React Event is always Istrusted:false
- Ag grid using framework cell renderer keeps re-rendering on any store change
- React / JavaScript - Optional hiding for menu options
- reactjs-how to get axios response data from parant component to a child component
- React test fails with IndexSizeError when setting rows on a textarea in useEffect
- ReactJS firebase.initializeApp is not a function
- axios could not be found within the project or in these directories: node_modules
- Can I use none-pure object as state in React?
- Link of react-router-dom updates the URL without rendering the component
- TypeError: Cannot read property 'name' of undefined error in a controlled-component
- How to build an edit form that depends on json
- React Material-UI override popover completely
- React rest-hooks how to Authentication
- When add new row of 2nd column , 1st row is row span in react.js
- Angular 6: continuously execute http request inside ngAfterContentChecked after receive data from parent component
- Create div elements dynamically within React component
- Dynamically generating query params with react-router v6 and useNavigate
- NPM - how to deploy a project on to a real server whenever there're some updates
- css every n-th img in new row
- Console error "Uncaught Error: Cannot find module "/axios" at webpackMissingModule" with react
- React: 'Maximum update depth exceeded' with FullCalendar
- Why Map value are not displaying inside modal body in react bootstrap
- How to route a details page of a photo when clicked in React?
- Blank page on npm start react
- can i call a component by clicking a button and can i directly pass a component inside the onclick event value?
- Adding an array and an object to an array react hooks
- How should i get the value from custom attribute in react element?
- React code splitting and server side rendering with System.import or require.ensure