Redux Form: Set error to a field without submitting the form - reactjs

I have a form that is loading data from an API. I'm trying to set manually an error to the field if occurs some error in the api call.
// This is the input that I'm trying to set the error message
<Field
name="username"
component={CustomCombobox}
/>
Here I'm trying to set an error in the catch block.
try {
const { data } = await UserService.getUser();
} catch (e) {
// here I'm trying to set an error to "username" field
stopSubmit('myFormName', { username: 'Something wrong happened.' })
}
But here's is the problem. I'm not submitting the form, so the stopSubmit does not work. I'm just receiving data from an API to fill the options, and if some error happens I want to set the error manually.

This website has some examples on form validation
If you are trying to run a check on the username before submitting the form, you could run an API call on the value of the field and then show the error if the function fails.
Maybe this isn't what you are looking for / I have misunderstood

Related

Nextjs Unable to setState after async function call

I have a Nextjs Form with fields like FirstName , Age and place to Upload Image.
After populating the form and uploading the image( saving uploaded File in the state variable using URL.createObjectURL() at this moment, works fine), i want to do the below steps :
First upload the image from state variable to cloudinary server.
After upload is complete, fetch the image url and setForm with rest of the fields.
//helper function to upload images to Cloudinary server
uploadImageToCloudinary(imageFile)
.then((res)=>{
setForm({
...form,
"picUploaded" : "true", //hard coded value for testing
"profilePic" : res.url //url is retrieved here successfully
});
//run validationafter upload to make sure required fields are there
let errs = validate();
setError(errs);
})
Validation Code
const validate= () => {
console.log(form.picUploaded);// Output : true
let err = {};
if(!form.firstName){
err.firstName= 'First Name is required.';
}
if(!form.lastName){
err.lastName= 'Last Name is required.';
}
if(!form.profilePic){ //Issue : Profile pic is not set here
err.profilePic= 'Profile Pic is required.';
}
return err;
}
Issue : The uploaded image url is not set in the form(field profilePic), but a hardcoded value picUploaded is set.
Can someone please guide me on what am i missing here.
The problem is you run the validation right after the setForm call, it's async so your validation will hit previous form values, not the new ones.
To avoid this you would need to run validation separately like so.
useEffect(() => {
setError(validate())
}, [form])
that will run validation on every form update, which is something you may or may not want, depending on the use case.
uploadImageToCloudinary(imageFile)
.then((res)=>{
setForm({
...form,
"picUploaded" : "true", //hard coded value for testing
"profilePic" : res.url //url is retrieved here successfully
});
})

Redux state is updated but UI is not updating

I have created simple app to add user using redux and antd library. When user is added I am trying to show success message. I am able to get that updated message in state but when I alert that message it shows blank. When I again click the button then it shows success message in alert.
I have created codesandbox link : https://codesandbox.io/s/admiring-waterfall-v04g9
Please help me out, I am quite new to react.
here is what possibly happened
- since your callback function is synchronous, eventhough the addUser function is placed before alert function, it is not a guarenty that it will execute before it.
solution is to make your function asynchronous as follows to guaranty that the user is added and hence state updated (with the user and the message you are displaying) before the alert is fired. make sure to save changes and refresh the sandbox to test it.
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields(async (err, values) => {
if (!err) {
await this.props.addUser(values);
alert(this.props.message);
}
});

This email already exists validation

I am making a React application where i submit the username, password and email to the mongo database.
Now I am trying to figure out how I could check inside of React whether the user or email already exists. Meaning so I could show an error-box telling the user to choose something else as an username.
I do know how to do it when I use Node.js and Handlebars. I know how to check my database with the Find() method of mongoose.
But I just don't understand how to think now that I am using React.
When I check if the user already exists in the back-end and it shows that it does exist, how could I inform my front-end (React) that it does?
When I use node.js and handlebars I use flash messages, and it works fine.
I guess my question could be summarized to, how should I do to get my React front-end to cooperate with my Node/Express back-end to share info about a username inside of the database already existing?
I have no code to show, this is more of asking for advice on what tools or methods I should use. I just can't figure it out.
Thank you in advance!
You'll need to have your back-end inform your front-end about whether or not an email has already been used since the front-end has no way of knowing without the back-end.
Basically, when a user tries to register, you should send your registration request from the front-end to the back-end without worrying about duplicate emails. The response from the server should indicate whether or not registration was successful, and if not, why not.
For example the registration component in your React code might look something like this:
class RegistrationComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
error: "",
}
}
handleSubmit = async event => {
event.preventDefault();
const { email, password } = this.state;
const response = await sendRegisterRequest(email, password);
const responseJson = await response.json();
if (response.status !== 200) {
this.setState({error: reponseJson.error});
} else {
// handle successful registration
}
}
render() {
const { error } = this.state;
return (
<form onSubmit={ this.handleSubmit }>
<span>{ error }</span>
{ /* rest of the form */ }
</form>
)
}
}
Where sendRegisterRequest is some module that handles sending registration requests to the server.
Note that this front-end logic expects the server to respond with status 200 on successful registration and with something else (status 400) if there is an error. Also if there is an error, the server should respond with a payload body that looks like: {"error": "That email is already in use"}.
You mention that you know how to check for existing email addresses on the server, so just check in that manner before creating a new account, and if the email address is already in use send the error payload with a status of 400.
You can respond with a 400 status if it occurs then send the error message to the frontend that way. e.g. return res.status(400).json(errors).
catch((err) => {
console.log(err);
if(err.status=404){
alert("email already used");
}

Chrome extension issue in block-chain transaction

Basically I want a chrome extension which takes data from block-chain and display in browser content-script also when user click on that data one transaction happen which will increase the count in block-chain.
I am able to retrieve data from block-chain please check the below code.
async componentDidMount(){
const ads = await advertiserAbi.methods
.getSpecificAdvertiserDetail(
"any address").call();
this.setState({ads});
}
But the problem is coming in performing transaction. Please check the below code.
async onSubmitForUpdate() {
console.log("Hello");
await userAbi.methods
.setStatistics("any address")
.send({
from: "any address"
});
}
Below is the error which I am getting.
POST https://rinkeby.infura.io/<--specific address--> 405 ()
Uncaught (in promise) Error: Invalid JSON RPC response: ""
at Object.InvalidResponse (content.js:108391)
at XMLHttpRequest.request.onreadystatechange (content.js:119211)

Custom remote validator error message

With a custom remote validator, how are you supposed to get rid of the error messages?
Using data-parsley-remote-validator='mycustom' on the field will give you an error in the console 'undefined async validator' unless the validator is added on DOM ready i.e not inside another function. However, if it is added on DOM ready, then parsley automatically calls it, which shouldn't happen until submit/change or whatever else you have set.
I can do something like this, but it kind of defeats the object of having parsley call the validator on change:
$('#signUpForm').on('submit', function() {
//add the attribute here to avoid the initial error message
$('#exampleInputEmail1').attr('data-parsley-remote-validator', 'validateEmail');
//then add the custom validator
$('#exampleInputEmail1').parsley()
.addAsyncValidator('validateEmail', function (xhr) {
if(xhr.status == '200') {
return 200;
}
// return the error message if email is taken
else if(xhr.status == '404') {
response = '<ul class="errorlist"><li>That email has already been taken, please try another</li></ul>'
$('#errorResponse').html(response);
}
}, '/api/v1/email/available', { "type": "POST", "dataType": "json", "data": data }
);
});
For those who came here for custom remote validator error message in Parsley.js,
You can add data-parsley-remote-message to the element,
<input type="text" data-parsley-remote-validator="my_remote_validator" data-parsley-remote-message="Custom error message only for remote validation on this element" >
Tested with Parsley.js - Version 2.3.11
Your asynch validator is not supposed to set an error message itself, it should simply return if the value validates or not. The error messages are added with a different API and/or specified as data attributes, check the doc.

Resources