Required input fields turn red after clear on submit. Reactjs - reactjs

I have a form which calls a redux action and then clears the input fields if the post was successful . The issue seems to be after the input fields are cleared on a successful post the input fields turn red.
redux action function
postActionFunction = (data, clearDataFunction) => (dispatch) => {
axios
.post(`/endpoint`, data)
.then(() => {
console.log('success');
})
.then(() => {
clearDataFunction();
})
.catch((err) => {
console.log('error');
});
};
form submit function
onSubmit(e) {
e.preventDefault();
const { inputData } = this.state;
// below function is the redux action
this.props.postCategories(inputData, this.clearDataFunction);
}
clearDataFunction() {
this.setState({ inputData: '' });
}
Edit :
This seems to happen only with Firefox developer's edition

Related

Why does it show firebase data as null at the first time? (React)

This part of the code is connected to onSubmit of the project
It works and fetches the data for logging from Firebase
But the problem is here, as soon as you log in for the first time, it shows null states, and when you click the second time, it fetches the data from the server.
Does anyone know what the problem is? Thank you.
const onSubmit = (event) => {
event.preventDefault();
if (handleValidation()) {
AXIOS.get("/MEMBERS/EMAILS.json")
.then((response) => {
for (const item in response.data) {
if (Username === response.data[item]) {
setIsLoggedIn(true);
break;
}
}
})
.catch((error) => {
alert(error);
});
AXIOS.get("/MEMBERS/PASSS.json")
.then((response) => {})
.catch((error) => {
alert(error);
});
}
};

How to add data to firestore document after creating user

I have a react application that should sign up a user and add the user's info to a collection using the uid. I am using redux and have broken my code into component, reducer and action. This is the add user component:
state = {
name : '',
email : '',
password : '',
position : '',
department : '',
}
handleChange = (e) => {
this.setState({
[e.target.id]: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault();
this.props.signUp(this.state)
}
render() {
return(//I have my input fields and submit button here)
}
const mapStateToProps = (state) => {
return {
auth: state.firebase.auth
}
}
const mapDispatchToProps = (dispatch) => {
return {
signUp: (newUser) => dispatch(signUp(newUser))
}
}
export default connect (mapStateToProps, mapDispatchToProps)(AddUser);
I do my auth action in the authAction with:
export const signUp = (newUser) => {
return (dispatch, getState, {getFirebase, getFirestore}) => {
const firebase = getFirebase();
const firestore = getFirestore();
firebase.auth().createUserWithEmailAndPassword(
newUser.email,
newUser.password
).then((resp) =>{
return firestore.collection('users').doc(resp.user.uid).set({
name: newUser.name,
position: newUser.position,
department: newUser.department
})
}).then(() => {
dispatch({ type: 'SIGNUP_SUCCESS' })
}).catch(err => {
dispatch({ type: 'SIGNUP_ERROR', err})
})
}
}
my Sign Up reducer is:
case 'SIGNUP_SUCCESS':
console.log('Signup success');
return {
...state,
authError: null
}
case 'SIGNUP_ERROR':
console.log('signup error');
return {
...state,
authError: action.err.message
}
The issue is that this creates a user and logs the user in but doesn't create a document with the user data in the firestore collection. I do not get any errors on the console. it also doesn't log the success message. The user is created and can log in though.
What am I doing wrong? Please help.
Thanks!
Do I understand right that it is an async process? If yes, you should also use Redux-Saga library for this(I mean it would be better practice).
However, if you are not willing to implement that try adding debugger or console log data in sign up action before return to see if you passing the right data in the right format for firebase. Same goes to catch block, console log error, I may say useful information if the error is in request/response.

This state not updating after a method returns in react

I currently have a class in react. For the sake of saving space I'm only putting the code that is relevant.
this.state = {
orgID: null,
memberID: null,
}
checkAuthUser = () => {
new Promise((resolve, reject) => {
this.props.firebase.auth.onAuthStateChanged(authUser => {
if(authUser) {
console.log(authUser);
resolve(authUser);
} else {
reject(new Error("Not authorized"));
}
})
})
.then( authDetails => {
this.props.firebase.getOrgID().on('value', snapshot => {
const setSnapshot = snapshot.val();
const getOrganizationID = Object.keys(setSnapshot)[0];
this.setState({ memberID: authDetails, orgID: getOrganizationID })
})
})
.catch(err => console.log(err))
}
render() {
if (this.state.orgID == null) {
try {
this.checkAuthUser();
console.log(this.state);
} catch (e) {
console.error(e);
}
}
In the class there's a method checkAuthUser . using firebase it checks whether a user has been signed in or not. If the user is signed in I console.log the object authUser. The console.log does log authUser details so I know it's hitting firebase and then returning the details. After I have a call to get some info from firebase.
I had added some console.logs to also confirm that it was running. However after the data comes back the console.log in render doesn't run anymore. The only console.log I get is the first initial state. What am I missing here?

Dispatching an action in react with redux

I don't know how can I easy resolve the problem. I have a form that user can fill and send stuff to my database. Form has his own state for it (here for example is just username). I don't know how to call setState (to give message to user about result) after dispatching redux action.
Function postDataBegin is simple and shows spinner only. I think there is a problem, cause this function is synchronous (tell me if not). How can i fix it? What should i learn?
submitForm = e => {
e.preventDefault();
const { username } = this.state;
if (!question) {
this.setState({ messageToUser: "Fill the form" });
} else {
// onSubmit is redux action from props
this.props.onSubmit(username);
//HOW TO CALL THIS FUNCTION AFTER FUNC ABOVE?
this.setState({ messageToUser: "Send" });
}
};
<Form type="submit" onSubmit={this.submitForm}/>
export const postUserQuestion = username => dispatch => {
dispatch(postDataBegin());
return post(postUsernameAPI, username)
.then(res => dispatch(postUsernameAPISucceeded(res)))
.catch(error => dispatch(postUsernameAPIFailure(error)));
};
Your action returns a promise, so you can use then method on it to provide a callback:
submitForm = e => {
e.preventDefault();
const { username } = this.state;
if (!question) {
this.setState({ messageToUser: "Fill the form" });
} else {
// onSubmit is redux action from props
this.props.onSubmit(username).then(() => {
this.setState({ messageToUser: "Send" });
});
}
};
Altho it'd probably be better to store that data on reducer as well, and change it the same time when the form is submitted.

Redux form submitSucceeded property is set to true before the submission fails

I am dispatching an action which makes an api call in redux-form asyncValidate method. The api call fails. I am trying to show the messages about successful and unsuccessful submit in the form, but submitSucceeded is always getting set to true before the api call fails. Therefore, I always get the message about successful submit before seeing the error message.
Before using asyncValidate, I tried the same thing inside onSubmit method. I throw an error inside the action, but that doesn`t help.
Here is the code for component:
const SubmissionForm = ({handleSubmit, submitFailed, submitSucceeded, asyncValidating}) =>
<Form onSubmit={handleSubmit}>
{submitFailed && <div>Failed</div>}
{submitSucceeded && <div>Succeeded</div>}
{asyncValidating && <div>Validating...</div>}
<Field name={`name`} type="text" component={"input"} />
</Form>
const enhancer = {
connect(null,{ editUser }),
reduxForm({
form: "editUser",
asyncBlurFields: [],
onSubmit: () => {},
asyncValidate: async (data, _, {editUser}) => {
return await editUser(data)
}
})
}
And the code for action:
const editUserStart = (user) => ({ type: EDIT_USER_START, user })
const editUserSuccess = (user) => ({ type: EDIT_USER_SUCCESS, user })
const editUserError = (error) => ({ type: EDIT_USER_ERROR, error })
const editUser = (data) => async dispatch => {
dispatch(editUserStart(data))
try {
const response = await api.postUserInfo(data)
if (response.error) {
throw new Error(response.error)
}else{
return dispatch(editUserSuccess(data))
}
} catch (e) {
dispatch(setSubmitFailed("editUser", e))
dispatch(editUserError(e))
}
}
How can I prevent the form from setting submitSucceeded before failing?
Probably your problem is with editUser function. Can you please console.log this const response = await api.postUserInfo(data) and make sure that response.error exists?

Resources