that's my connect page's form. it works great. but i want to validate in validation function line (validate() ) ,too. however, it is sending mail even though empty inputs.
i think, i have to add something in handleSubmit line with isValid line.
what should I do?
const initialState={
name: "",
subject: "",
email: "",
message: "",
sent:false,
nameError: "",
}
export default class Validation extends React.Component {
state = initialState;
handleName = (e) => {
this.setState({
name:e.target.value
})
}
validate = () => {
let nameError= "";
if (!this.state.name) {
nameError = "Name cannot be blank!"
}
if (nameError) {
this.setState({ nameError });
return false;
}
return true;
}
handleSubmit = (e) => {
e.preventDefault();
const isValid = this.validate();
if (isValid) {
console.log(this.state);
}
this.sendingMail();
}
sendingMail=()=>{
let data = {
name:this.state.name,
}
axios.post('http://localhost:3001/api/form',data)
.then(res=>{
this.setState({
sent:true,
},this.resetForm())
})
.catch(()=> {
console.log('message not sent');
})
}
Related
I have a main view where users login/register to see movies and the login view page has a function that when you submit, is supposed to query the function in main view.
Main View:
export class MainView extends React.Component {
constructor(props) {
super(props);
// Initial state is set to null
this.state = {
movies: [],
user: null
};
}
componentDidMount() {
let accessToken = localStorage.getItem("token");
if (accessToken !== null) {
this.setState({
user: localStorage.getItem("user"),
});
this.getMovies(accessToken);
}
}
/* When a user successfully logs in, this function updates the `user` property in state to that *particular user*/
onLoggedIn(authData) {
console.log(authData);
this.setState({
user: authData.user.Username,
});
localStorage.setItem("token", authData.token);
localStorage.setItem("user", authData.user.Username);
this.getMovies(authData.token);
}
onLoggedOut() {
localStorage.removeItem("token");
localStorage.removeItem("user");
this.setState({
user: null,
});
}
getMovies(token) {
axios
.get(`https://app.herokuapp.com/movies`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => {
// Assign the result to the state
this.setState({
movies: response.data,
});
})
.catch(function (error) {
console.log(error);
});
}
Login View:
export function LoginView(props) {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
// Declare hook for each input
const [usernameErr, setUsernameErr] = useState("");
const [passwordErr, setPasswordErr] = useState("");
// validate user inputs
const validate = () => {
let isReq = true;
if (!username) {
setUsernameErr("Username required");
isReq = false;
} else if (username.length < 2) {
setUsernameErr("Username must be at least 2 characters long");
isReq = false;
}
if (!password) {
setPasswordErr("Password required");
isReq = false;
} else if (password.length < 6) {
setPassword("Password must be at least 6 characters long");
isReq = false;
}
return isReq;
};
const handleSubmit = (e) => {
e.preventDefault();
const isReq = validate();
if (isReq) {
/* Send request to the server for authentication */
axios
.post(`https://app.herokuapp.com/login`, {
Username: username,
Password: password,
})
.then((response) => {
const data = response.data;
props.onLoggedIn(data);
})
.catch((error) => {
console.log(error, "no such user");
});
}
};
For some reason it tells me that props.onLoggedIn is not a function, which I have already imported in to MainView (I mean LoginView) which should recognise the function. Is there anything that I am missing?
I am trying to prevent users from login in twice and creating 2 sessions (when they press log in button twice very fast). I am thinking of disabling button after it was click and the enabling it after approx. 2 sec in case there was an error e.g. "password incorrect" so that users can reenter their details and send form again. I do currently have onSbumit function (code below) and when I implement onclick disable button it wont send as button is getting disabled before the form is submitted.
What is the best approach to solve that issue? Code of by onSubmit function below:
handleFormSubmission = (event) => {
event.preventDefault();
const credentials = {
username: this.state.username,
password: this.state.password,
};
if (!this.state.username.trim()) {
this.setState({
errorUsername: "*Enter your username.",
});
}
if (!this.state.password.trim()) {
this.setState({
errorPassword: "*Enter your password.",
});
}
if (this.state.username.trim() && this.state.password.trim()) {
this.setState({
buttonDisable: true,
});
login(credentials).then((res) => {
this.setState({
buttonDisable: false,
});
if (!res.status) {
this.setState({
error: res.errorMessage,
});
} else {
localStorage.setItem("accessToken", res.data.accessToken);
this.props.authenticate(res.data.user);
this.setState({
buttonDisabled: true,
});
this.props.history.push("/");
}
});
}
};
The implementation of the function onClick isn't necessary, the solution is to stop the user to submit the form twice is to disable the button when you send the data to the server and when you get the response you enable the button:
handleFormSubmission = (event) => {
event.preventDefault();
const credentials = {
username: this.state.username,
password: this.state.password,
};
if (!this.state.username.trim()) {
this.setState({ errorUsername: "*Enter your username."});
}
if (!this.state.password.trim()) {
this.setState({ errorPassword: "*Enter your password."});
}
if (this.state.username.trim() && this.state.password.trim()) {
setState({
disableButton: true
}) //Disable your button here
login(credentials).then((res) => {
setState({
disableButton: false
}) //enable your button
if (!res.status) {
this.setState({error: res.errorMessage});
} else {
localStorage.setItem("accessToken", res.data.accessToken);
this.props.authenticate(res.data.user);
this.props.history.push("/");
}
});
}
};
So, I am wanting to retrieve an updated list of contacts on once a new contact is added. Unfortunately, axios is only loading the get request on the 'beforeMount()' instance. When I try and call the function inside of an axios.post request when it's successful, the list of contacts is gone until I refresh the page again.
I'm running Laravel 5.7 and VueJs 2.5.22.
import axios from 'axios';
export default {
data() {
return {
companion: {
name: '',
desc: '',
primaryPhone: '',
secondaryPhone: '',
email: '',
address: '',
notes: '',
image: ''
},
characterAmount: 0
};
},
props: {
addCompanion: {
type: Boolean
}
},
methods: {
checkNotesLength(e) {
this.characterAmount =
document.getElementById('notes').value.length;
if (e.keyCode === 8) {
this.characterAmount--;
if (this.characterAmount < 0) {
this.characterAmount = 0;
}
} else {
this.characterAmount++;
if (this.characterAmount > 150) {
this.characterAmount = 150;
}
}
},
processFile(e) {
var input = e.target;
var reader = new FileReader();
reader.onload = (e) => {
this.companion.image = e.target.result;
}
reader.readAsDataURL(input.files[0]);
},
getCompanions() {
const url = window.location + 'companions';
axios.get(url)
.then((response) => {
this.companions = response.data;
})
.catch((error) => {
// handle error
console.log(error);
});
},
submitCompanion() {
const formData = {
name: this.companion.name,
desc: this.companion.desc,
primaryPhone: this.companion.primaryPhone,
secondaryPhone: this.companion.secondaryPhone,
email: this.companion.email,
address: this.companion.address,
notes: this.companion.notes,
image: this.companion.image
}
axios.post('/companion/create', formData)
.then(this.getCompanions())
.then((response) => {
this.addCompanion = !this.addCompanion;
//need to clear form and include messages, also need to add validation
})
.catch((error) => {
console.log(error);
});
}
}
}
The beforeMount() function is on my App.vue, which just calls the same getCompanions function as the above one you see.
The issue that I see in your code is that you are not passing the callback correctly. This code will execute the function getCompanions() immediately:
.then(this.getCompanions())
To pass it as a callback try something like this
.then(this.getCompanions.bind(this))
// OR
.then(() => this.getCompanions())
This is probably because your url structure is wrong.
const url = window.location + 'companions';
should be
const url = window.location + '/companions';
import getAuthentication from './getAuthentication';
class Home extends React. Component {
constructor() {
super();
//this.authentication = false;
this.state = {
username: '',
password: '',
check:false,
authentication:false
};
this.err = '';
}
componentDidUpdate() {
console.log (this.state.authentication);
console.log(this.state.authentication == true);
if (this.state.check)
{
const promiseAuthentication = getAuthentication(
this.state.username,
this.state.password,
);
promiseAuthentication
.then(response => {
console.log (response.data.Success);
console.log(response.data.Success == true);
this.setState({check :false, authentication:response.data.Success});
})
.catch(error => {
// console.log(error);
this.err = error;
});
}
if (this.state.authentication == true) {
event.preventDefault();
history.push('/overview');
}
}
assignUsername = event => {
this.setState({ username: event.target.value });
};
assignPassword = event => {
this.setState({ password: event.target.value });
};
handleSubmit = () => {
this.setState({ check:true });
};
==============================================================
getAuthentication.js
import axios from 'axios';
function getAuthentication(username, password) {
const authenticationConfig = {
Email: username,
Password: password,
};
return axios.post(
'http://localhost:5002/login/confirmation',
authenticationConfig,
);
}
export default getAuthentication;
In the above code my this.state.Authentication is not getting updated to true
I am trying to update its value in axios promise.
Can someone please tell me what's wrong? I mean I have tried everything but I am not able to proceed.
How do I change the state of Authentication object and switch new window?
I have a second file that is returning the axios promise where promise value is "undefined".. How do I make async call and resolve this issue ??
componentDidUpdate is wrapped in if (this.state.check). Nothing in the code you pasted sets this.state.check to true. Set this.state.check: true.
I've a Vue component as follows:
import '../forms/form.js'
import '../forms/errors.js'
export default{
data(){
return{
form: new NewForm({
email: '',
password: '',
intendedUrl: '',
message: ''
})
}
},
methods: {
/**
* Login the user
*/
login(e) {
e.preventDefault();
this.form.startProcessing();
this.$http.post('/login/authenticate', this.form)
.then(function(response) {
this.form.finishProcessing();
},
function(response) {
this.form.setErrors(response.data);
});
}
}
}
The form.js file is
window.NewForm = function (data) {
var form = this;
$.extend(this, data);
this.errors = new NewFormErrors();
this.busy = false;
this.successful = false;
this.startProcessing = function () {
form.errors.forget();
form.busy = true;
form.successful = false;
};
this.setErrors = function (errors) {
console.log('okkk');
form.busy = false;
form.errors.set(errors);
}
};
and error.js
window.NewFormErrors = function () {
this.errors = {};
this.set = function (errors) {
console.log(errors);
this.errors= errors;
};
};
Here, the this.form.startProcessing(); seems working. But I'm not able to get the data passed to the this.setErrors. console.log(errors) returns nothing. Or it's not getting executed.
I have not recreated all of your solution but I will suspect the meaning of the value of this in the deferred execution so I will try to modify the code to:
login(e) {
e.preventDefault();
var that = this ;
this.form.startProcessing();
this.$http.post('/login/authenticate', this.form)
.then(function(response) {
that.form.finishProcessing();},
function(response) {
that.form.setErrors(response.data); });
}
I hope it will help.