Not recognizing the user after I receive a request from React - javascript

After I send data in json I want to save the data, all the data is received fine, but it does not recognize the user, even though it is indeed connected according to the tests I did. i am getting this error: ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x106fd12d0>>": "Vendors.user" must be a "User" instance.
but the user is log in.
view.py:
#csrf_exempt
def store_register(request):
if request.method == 'POST':
form = json.loads(request.body)
print(request.user,form)
vendor = Vendors.objects.create(user=request.user,store_name=form['storeName'],company_name=form['companyName'],img=form['storeImage'],business_email=form['businessEmail'],pay_pal=form['payPalEmail'])
vendor.save()
return JsonResponse({'test':'test'})
react:
class RegisterBody extends React.Component {
constructor (props) {
super (props);
this.state = {
url: ''
}
}
SendInput = () => {
const storeName = document.getElementById('storeName').value
const companyName = document.getElementById('companyName').value
const storeImage = document.getElementById('storeImage').value
const businessEmail = document.getElementById('businessEmail').value
const payPalEmail = document.getElementById('payPalEmail').value
this.setState({storeName:storeName,companyName:companyName,storeImage:storeImage,businessEmail:businessEmail,payPalEmail:payPalEmail})
fetch('/store-register', {
method: 'POST',
body: JSON.stringify({
'storeName':storeName,
'companyName':companyName,
'storeImage':storeImage,
'businessEmail':businessEmail,
'payPalEmail':payPalEmail
}),
headers: {
'Content-type': 'application/json; charset=UTF-8'
},
})
}
render () {
return (
<div>
<label>Store Name</label>
<input type={"text"} name={"storeName"} id={"storeName"}></input>
<br></br>
<label>Company Name</label>
<input type={"text"} name={"companyName"} id={"companyName"}></input>
<br></br>
<label>Store Image</label>
<input type={"file"} name={"storeImage"} id={"storeImage"}></input>
<br></br>
<label>Business Email</label>
<input type={"email"} name={"businessEmail"} id={"businessEmail"}></input>
<br></br>
<label>Paypal Email</label>
<input type={"email"} name={"payPalEmail"} id={"payPalEmail"}></input>
<br></br>
<button onClick={() => this.SendInput()}>Register</button>
</div>
)
}
}
export default RegisterBody

Related

How to append multiple files to formData?

I have a form, and I have an input in the form, I upload several images in this input, like so:
<input type="file" name="gallery" onChange={imageHandler} required multiple />
And when I output the images in the console, it correctly displays an array of files, but when I append the images, formData.append("gallery", images); it is not saved as an array. It's saved as a File!
const [selectedFile, setSelectedFile] = useState();
const [images, setImages] = useState([]);
const token = localStorage.getItem("TOKEN");
const imageHandler = (e) => {
setImages([...images, e.target.files[0]]);
};
useEffect(() => {
images.length && console.log(images);
}, [images]);
console.log(images);
const sendDisease = async (e) => {
e.preventDefault();
console.log(images);
const form = document.getElementById("signUpForm");
const formData = new FormData(form);
formData.append("gallery", images);
console.log(formData);
try {
const api = "https://localhost/api/v1/website/disease/add";
const { data } = await axios.post(api, formData, {
headers: {
headers: { "Content-Type": "multipart/form-data" },
Authorization: `Bearer ${token}`,
},
});
toast.success(data.message, { autoClose: 15000 });
} catch (e) {
console.log(e);
toast.error(e.response.data.error, { autoClose: 15000 });
console.log(e.response.data.error);
}
};
const handleFileSelect = (event) => {
setSelectedFile(event.target.files[0]);
};
return (
<>
<div className="container">
<div className="row">
<form id="signUpForm" className="md-12">
<h2 className="text-center mb-4 font-weight-bold">Add Disease</h2>
<div className="form-row mt-4">
<div className="col-md-6 mb-3">
<label for="">Add Disease</label>
<input
type="text"
className="form-control"
name="unique_name"
required
onChange={(e) => setUniqueName(e.target.value)}
/>
</div>
<div className="col-md-6 mb-3">
<label for="">Title</label>
<input
type="text"
className="form-control"
name="title"
placeholder="Title"
onChange={(e) => setTitle(e.target.value)}
required
/>
</div>
</div>
<div className="form-row">
<div className="col-md-12 mb-3">
<label for="">Gallery</label>
<input type="file" name="gallery" onChange={imageHandler} required multiple />
</div>
</div>
<input type="file" name="image" onChange={handleFileSelect} />
</div>
<button
type="button"
className="btn btn-primary mt-4"
onClick={sendDisease}
>
Submit
</button>
</form>
</div>
</div>
</>
);
Calling new FormData(form) is enough. You don't need to call formData.append("gallery", images) as the constructor will pick on its own all the images for you. So you may not even need this images state.
The code below would log all your files if you wanna be sure about it. I also created a working Codesandbox for testing.
export default function App() {
const handleSubmit = (e) => {
e.preventDefault();
const form = document.getElementById("signUpForm");
const formData = new FormData(form);
console.log(formData.getAll("gallery"));
};
return (
<form id="signUpForm" onSubmit={handleSubmit}>
<input type="file" name="gallery" required multiple />
<button>Sumbit</button>
</form>
);
}
If it's not working, try changing formData.append("gallery", images) to the code below (it's apparently what's needed for PHP servers for example):
images.forEach((image) => {
formData.append('gallery[]', image);
});
Here in my case Am using ASP.NET Core and its working fine
images.forEach((image) => {
formData.append('images', image);
});
My Controller
[HttpPost]
public async Task<IActionResult> UpdateProfile([FromForm] UpdateProfileModel updateProfileModel)
{
try
{
await Task.CompletedTask;
return Ok("Done.");
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
My Modal
public class UpdateProfileModel
{
public List<IFormFile> Images { get; set; } = new List<IFormFile>();
}

How to post data to supabase through next.js

I currently have a simple next.js website where users can look at projects for an organization, and at the bottom of the page, the user can input a new project through the use of a form with multiple inputs. The database that i am currently using is Supabase.
My code currently takes in user input from each input box and stores them inside the newProject const, after which the data is then parsed into the createNewProject function and sent to Supabase.
const initialState = { solution_id: '', organization_id: '', budget_usd: '',other_info: '',country: '',project_duration_days: '',status: '',date_time_timezone: '' }
export default function Projects({ Projects }) {
useEffect(() => {
console.log(Projects)
}, [])
const [newProject, setProject] = useState(initialState)
console.log("User inputed data")
console.log(newProject)
const {solution_id, organization_id, budget_usd, other_info, country,project_duration_days,status,date_time_timezone} = newProject
const router = useRouter()
function onChange(e) {
setProject(() => ({ ...newProject, [e.target.name]: e.target.value }))
}
async function createNewProject() {
if (!solution_id || !organization_id || !country) return
const id = uuid()
newProject.id = id
const {data} = await supabase
.from('Projects')
.insert([
{ solution_id, organization_id, budget_usd,other_info,country,project_duration_days,status,date_time_timezone }
])
router.push(`/projects/${data.id}`)
}
return (
<div>
{Projects.map(project => {
return (
<div key={project.id}>
<h1><b>{project.Solutions.name} in {project.country}</b></h1>
<h2>Budget USD: {project.budget_usd}</h2>
<h2>Duration: {project.project_duration_days} days</h2>
<h2>Status: {project.status}</h2>
<h2>Organization: {project.Organizations.name}</h2>
<h2>Project Id: {project.id}</h2>
<button type="button" onClick={() => router.push(`/projects/${project.id}`)}>Donate now</button>
<br></br>
</div>
)
})}
<label htmlFor="solution_id ">solution_id</label>
<input onChange={onChange} value={newProject.solution_id} type="text" id="solution_id" name="solution_id" required />
<label htmlFor="organization_id ">organization_id</label>
<input onChange={onChange} value={newProject.organization_id} type="text" id="organization_id" name="organization_id" required />
<label htmlFor="budget_usd ">Last budget_usd</label>
<input onChange={onChange} value={newProject.budget_usd} type="text" id="budget_usd" name="budget_usd" required />
<label htmlFor="other_info ">other_info</label>
<input onChange={onChange} value={newProject.other_info} type="text" id="other_info" name="other_info" required />
<label htmlFor="country ">country</label>
<input onChange={onChange} value={newProject.country} type="text" id="country" name="country" required />
<label htmlFor="project_duration_days ">Project Duration Days</label>
<input onChange={onChange} value={newProject.project_duration_days} type="text" id="project_duration_days" name="project_duration_days" required />
<label htmlFor="status ">status</label>
<input onChange={onChange} value={newProject.status} type="text" id="status" name="status" required />
<label htmlFor="date_time_timezone ">date_time_timezone</label>
<input onChange={onChange} value={newProject.date_time_timezone} type="text" id="date_time_timezone" name="date_time_timezone" required />
<button type="button" onClick={createNewProject} >Submit new project</button>
</div>
)
}
export async function getServerSideProps() {
const fetchOrgs = async () => {
let { data: Organizations, error } = await supabase
.from('Organizations')
.select('*')
return Organizations
}
const fetchSolutions = async () => {
let { data: Solutions, error } = await supabase
.from('Solutions')
.select('*')
return Solutions
}
const fetchProjects = async () => {
let { data: Projects, error } = await supabase
.from('Projects')
.select(`
id,
solution_id,
organization_id,
budget_usd,
country,
project_duration_days,
status,
Solutions(name),
Organizations(name)
`)
.order('id', { ascending: true })
console.log(Projects)
return Projects
}
const Organizations = await fetchOrgs();
const Solutions = await fetchSolutions();
const Projects = await fetchProjects();
return { props: { Solutions, Organizations, Projects } }
}
However, whenever I press the submit button, the console.log for the newProject, would show that there is not data being passed into the variables, only the empty placeholder data in the initialState const. As such, I am unsure about how to pass data from next.js input forms into a variable to be posted into supabase.

How to bypass a input file when is not uploaded in VueJS/Axios

I'm making a VueJS blog; I'm working with the update page and everything is working except the input file field: It works only if you'll upload a file, if you don't upload it the console return this error:
Uncaught TypeError: Failed to execute 'append' on 'FormData':
parameter 2 is not of type 'Blob'.
Else, I've tried to make an if state with a variable and a boolean field but in this way the image never uploads (but it not gave any error in console and it make the form working if you don't upload an image). I'll put below the code with and without the if statement. The Backend is made with Django and Django Rest framework.
VueJS without the If statement (1st example)
<template>
<main>
<SideBar></SideBar>
<section>
<h3>Edit {{ form.title }}</h3>
<form #submit.prevent = "onSubmit" enctype="multipart/form-data">
<input type="text" name="title" placeholder="Titolo" v-model="form.title">
<input type="text" name="category" v-model="form.category">
<textarea type="text" name="desc" placeholder="Descrizione" v-model="form.desc"> </textarea>
<textarea name="text" v-model="form.text"></textarea>
<input type="file" name="image" #change="EditImage">
<input type="text" name="author" v-model="form.author">
<input type="text" name="author" v-model="form.slug">
<button type="submit">Edit</button>
</form>
</section>
</main>
</template>
<script>
import axios from 'axios';
import { getAPI } from '../api'
import SideBar from '../components/Admin/Sidebar.vue';
import swal from 'sweetalert'
export default {
components: {
'SideBar': SideBar
},
data () {
return{
Postslug: this.$route.params.Postslug,
form: {
title:"",
desc:"",
text:"",
category:"",
date:"",
author:"",
image:"",
slug:"",
},
}
},
methods: {
EditImage(event){
this.form.image = event.target.files[0]
},
// Form method
onSubmit(event, imageSelection){
console.log(imageSelection);
const fd = new FormData();
fd.append('title', this.form.title)
fd.append('desc', this.form.desc)
fd.append('text', this.form.text)
fd.append('category', this.form.category)
fd.append('date', this.form.date)
fd.append('author', this.form.author)
fd.append('image', this.form.image, this.form.image.name)
fd.append('slug', this.form.slug)
// event.preventDefault();
axios.patch(`http://127.0.0.1:8000/blog/api/edit/${this.Postslug}`, fd).then(response => {
this.form.title = response.data.title
this.form.desc = response.data.desc
this.form.text = response.data.text
this.form.image = response.data.image
this.form.category = response.data.category
this.form.author = response.data.author
this.form.slug = response.data.slug
this.$router.push({ name: 'AdminEditArticle', params: {Postslug: this.form.slug } });
swal("Articolo editato", "", "success")
.then(() => {
window.location.reload()
})
.catch(() => {
swal("Problema", "", "warning")
});
})
.catch(err => {
})
},
},
created() {
getAPI.get(`blog/api/edit/${this.Postslug}`)
.then(response => {
this.form.title = response.data.title
this.form.desc = response.data.desc
this.form.text = response.data.text
this.form.date = response.data.date
this.form.image = response.data.image
this.form.category = response.data.category
this.form.author = response.data.author
this.form.slug = response.data.slug
})
.catch(err => {
console.log(err)
})
},
name: 'AdminEditArticle',
}
</script>
<style lang="sass" scoped>
stuff...
</style>
Code with the if statement (2nd example)
<template>
<main>
<SideBar></SideBar>
<section>
<h3>Edit {{ form.title }}</h3>
<form #submit.prevent = "onSubmit" enctype="multipart/form-data">
<input type="text" name="title" placeholder="Titolo" v-model="form.title">
<input type="text" name="category" v-model="form.category">
<textarea type="text" name="desc" placeholder="Descrizione" v-model="form.desc"> </textarea>
<textarea name="text" v-model="form.text"></textarea>
<input type="file" name="image" #change="EditImage">
<input type="text" name="author" v-model="form.author">
<input type="text" name="author" v-model="form.slug">
<button type="submit">Edit</button>
</form>
</section>
</main>
</template>
<script>
import axios from 'axios';
import { getAPI } from '../api'
import SideBar from '../components/Admin/Sidebar.vue';
import swal from 'sweetalert'
let imageSelection = false;
export default {
components: {
'SideBar': SideBar
},
data () {
return{
Postslug: this.$route.params.Postslug,
form: {
title:"",
desc:"",
text:"",
category:"",
date:"",
author:"",
image:"",
slug:"",
},
}
},
methods: {
EditImage(event){
this.form.image = event.target.files[0]
let imageSelection = true
return imageSelection
},
// Form method
onSubmit(event, imageSelection){
console.log(imageSelection);
const fd = new FormData();
fd.append('title', this.form.title)
fd.append('desc', this.form.desc)
fd.append('text', this.form.text)
fd.append('category', this.form.category)
fd.append('date', this.form.date)
fd.append('author', this.form.author)
if (imageSelection == true) {
fd.append('image', this.form.image, this.form.image.name)
}
fd.append('slug', this.form.slug)
// event.preventDefault();
axios.patch(`http://127.0.0.1:8000/blog/api/edit/${this.Postslug}`, fd).then(response => {
this.form.title = response.data.title
this.form.desc = response.data.desc
this.form.text = response.data.text
this.form.image = response.data.image
this.form.category = response.data.category
this.form.author = response.data.author
this.form.slug = response.data.slug
this.$router.push({ name: 'AdminEditArticle', params: {Postslug: this.form.slug } });
swal("Articolo editato", "", "success")
.then(() => {
window.location.reload()
})
.catch(() => {
swal("Problema", "", "warning")
});
})
.catch(err => {
})
},
},
created() {
getAPI.get(`blog/api/edit/${this.Postslug}`)
.then(response => {
this.form.title = response.data.title
this.form.desc = response.data.desc
this.form.text = response.data.text
this.form.date = response.data.date
this.form.image = response.data.image
this.form.category = response.data.category
this.form.author = response.data.author
this.form.slug = response.data.slug
})
.catch(err => {
console.log(err)
})
},
name: 'AdminEditArticle',
}
</script>
<style lang="sass" scoped>
stuff...
</style>
Thanks for the help
The problem is you are trying to save an image with your form.
For this to work, you should first upload the file and then take the imagePath(where you uploaded it) and save the path in your form.
So in your submit function, you should make a post request to upload the image and take the response which will be the image path on your server and save it in your form object.
Example :
onSubmit() {
if(checkIfCreateOrEdit)
createPost(this.form).then(res => {
if (this.form.image instanceof File) {
const formData = new FormData()
formData.append('imagePhoto', this.form.image)
return axios.post(url, headers: 'Content-Type':'multipart/form-data', data: formData)
})
.then(()=> this.$router.push(....) )
.catch(....)
} else {
editPost(this.form, this.post.id){
.....the same as above but you make a put request based on the id
}
}
Notes:
Try to use destructure on your form object.
In order to show the image on your template after you have submitted the form, you should recreate the imagePath and pass it as src attribute.

REACTJS AND API pass the value of Api to another page

I really need help cause I'm totally new to reactjs. How can I maintain the logged-in user throughout the page? like a session. the code shows the data called when I logged in. I'm really lost here in react.
When the credentials are true, here's the result
{userId: 1, firstname: "Jeff", middlename: null, lastname: "Geli", positionId: 1, …}
userId: 1
firstname: "Jeff"
middlename: null
lastname: "Geli"
positionId: 1
token: "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJMb2dnZWRVc2VyIjoie1wiVXNlcklkXCI6MSxcIkZpcnN0bmFtZVwiOlwiSmVmZlwiLFwiTWlkZGxlbmFtZVwiOm51bGwsXCJMYXN0bmFtZVwiOlwiR2VsaVwiLFwiUG9zaXRpb25JZFwiOjEsXCJUb2tlblwiOm51bGx9IiwiZXhwIjoxNTc5NzU5MzI5LCJpc3MiOiJzbWVzay5pbiIsImF1ZCI6InJlYWRlcnMifQ.xXPW0ijBdULuMBfhFGyL1qF1bA--FzG64jEJVMQZWY8"
__proto__: Object
import React from 'react';
import { Link, withRouter } from 'react-router-dom';
import { PageSettings } from './../../config/page-settings.js';
import bg from '../../assets/login-bg-17.jpg';
import axios from "axios";
class LoginV2 extends React.Component {
static contextType = PageSettings;
constructor(props) {
super(props);
//credentials for login
this.state = {
username: '',
password: '',
};
this.handleSuccess = this.handleSuccess.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.context.handleSetPageSidebar(false);
this.context.handleSetPageHeader(false);
}
componentWillUnmount() {
this.context.handleSetPageSidebar(true);
this.context.handleSetPageHeader(true);
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
};
handleSuccess(data) {
alert("Logged IN");
this.props.history.push('dashboard/v2');
}
//When submit button is clicked, fetch API
async handleSubmit(event) {
event.preventDefault();
//fetch API, method POST
const getCred = await fetch('/api/login', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'ApiKey': "Secret"
},
method: "POST",
body: JSON.stringify({
username: this.state.username,
password: this.state.password
}),
});
const data = await getCred.json();
if (getCred.status == 400) {
alert(data);
} else {
this.handleSuccess(getCred);
}
console.log(data);
}
render() {
return (
<React.Fragment>
<div className="login-cover">
<div className="login-cover-image" style={{backgroundImage:'url('+ bg +')'}} >
</div>
<div className="login-cover-bg"></div>
</div>
<div className="login login-v2">
<div className="login-header">
<div className="brand">
<span className="logo"></span> <b>Tek</b> Teach
<small>Leraning Management System</small>
</div>
<div className="icon">
<i className="fa fa-lock"></i>
</div>
</div>
<div className="login-content">
<form className="margin-bottom-0" onSubmit={this.handleSubmit}>
<div className="form-group m-b-20">
<input type="text" className="form-control form-control-lg" placeholder="Username" name="username" value={this.state.username} onChange={this.handleChange} required />
</div>
<div className="form-group m-b-20">
<input type="password" className="form-control form-control-lg" placeholder="Password" name="password" value={this.state.password} onChange={this.handleChange} required />
</div>
<div className="login-buttons">
<button type="submit" className="btn btn-success btn-block btn-lg" onClick={this.login}>Sign me in</button>
</div>
</form>
</div>
</div>
</React.Fragment>
)
}
}
export default withRouter(LoginV2);
You could use sessionStorage or localStorage to store the token and then check for it, if it is set then keep user logged in otherwise logout user.
set the session once user logged in
if (token) {
localStorage.setItem('session', JSON.stringify(token));
}
To check if the user is logged in
let user = localStorage.getItem('session');
if (user) {
console.log('Valid session');
} else {
console.log('Not valid session');
}
On logut clear the value
let user = localStorage.getItem('session');
if (user) {
localStorage.removeItem();
}
Adding the logic in the provided code
async handleSubmit(event) {
// .... Other code
const data = await getCred.json();
if (data.status == 400) {
alert(data);
} else {
this.handleSuccess(data);
}
console.log(data);
}
//Set your token in handleSuccess method
handleSuccess(data) {
alert("Logged IN");
if (data.token) {
localStorage.setItem('session', JSON.stringify(data.token));
}
this.props.history.push('dashboard/v2');
}

If Else in react component always run else condition

I am trying to build a contact form where an if else statement checks the validity of the email address entered, then with a nested if else checks whether the honeypot filed has a value and sends an ajaxj post request to an aws api gateway.
The ajax post runs without problem, but the outer else is always run.
Here the code:
import React from 'react'
import './style.scss'
const $ = require('jquery')
class ContactForm extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
email:'',
subject:'',
message:'',
honeypot:'',
result:'',
alertType:'',
formErrors:{
email:'',
name:'',
message:''
},
isFormValid:false,
emailValid:false,
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const target = event.target
const value = target.value
const name = target.name
this.setState({ [name]: value })
}
handleSubmit(event) {
event.preventDefault();
var URL = "https://someaddress/";
var form =this
var data = {
name: this.cleanInput(this.state.name.trim()),
email: this.cleanInput(this.state.email.trim()),
subject: this.cleanInput(this.state.subject.trim()),
message: this.cleanInput(this.state.message.trim()),
}
this.validateField('email',data.email)
data.message = "Bilgiler şunlar:\nAdı:"+data.name+"\nEmail Adresi: "+data.email+"\nKonu:"+data.subject+"\nMesaj:"+data.message
data.subject = "[Bestpet Web Sitesinden Doldurulan Form] "+data.subject;
data.email = "info#atlaspet.com.tr";
if(this.state.emailValid ===true){
if (this.state.honeypot=== ''){
$.ajax({
type: "POST",
url: URL,
dataType: "json",
contentType: "application/json",
data: JSON.stringify(data),
success: function(){
form.setState({name:'',email:'',message:'',subject:'',result:'Form başarıyla gönderildi.',alertType:'alert alert-success'})
},
error: function () {
// show an error message
form.setState({result: 'Sorunlar oluştu. Formu gönderemedik.',alertType:'alert alert-danger'});
},
});
} else {console.log("Hi there, I guess you are not human baby");}
} else { form.setState({result: 'Lütfen girmiş olduğunuz email adresini kontrol ediniz.',alertType:'alert alert-danger'})}
}
validateField(fieldName, value) {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
;
switch (fieldName) {
case 'email':
emailValid = value.match(/^([\w.%+-]+)#([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.email = emailValid ? true : false;
break;
default:
break;
}
this.setState({
formErrors: fieldValidationErrors,
emailValid: fieldValidationErrors.email
}, this.validateForm);
console.log(this)
}
validateForm() {
this.setState({ isFormValid: this.state.emailValid });
}
cleanInput(input){
var search = [
'<script[^>]*?>.*?</script>', // Strip out javascript
'<[/!]*?[^<>]*?>', // Strip out HTML tags
'<style[^>]*?>.*?</style>', // Strip style tags properly
'<![sS]*?--[ \t\n\r]*>', // Strip multi-line comments
]
var text = input
// console.log(search.length)
//var output = preg_replace($search, '', input);
for (let i = 0; i < search.length; i++) {
text = text.replace(new RegExp(search[i], 'gi'), '')
}
return text
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<div className={"col-md-12 "+this.state.alertType}>{this.state.result!=='' && this.state.result}</div>
<input name="honeypot" type="text" style={{display:"none"}} value={this.state.honeypot} onChange={this.handleChange}/>
</div>
<div className="form-group">
<div className="col-md-6">
<label>
Name:
{this.state.formErrors.name!=='' && <div className="col-md-12 alert alert-danger">'Sizinle iletişim kurabilmemiz için bir isim girmelisiniz'</div>}
<input name="name" type="text" value={this.state.name} className ="form-control required" onChange={this.handleChange} />
</label>
</div>
<div className="col-md-6">
<label>
email
<input type="text" name="email" className="form-control required" value={this.state.email} onChange={this.handleChange}/>
</label>
</div>
</div>
<div className="form-group">
<div className="col-md-12">
<label>
Subject
<input type="text" name="subject" className="form-control required" value={this.state.subject} onChange={this.handleChange}/>
</label>
</div>
</div>
<div className="form-group">
<div className="col-md-12">
<label>
Message
<textarea name="message" rows="6" className="form-control required" value={this.state.message} onChange={this.handleChange}/>
</label>
</div>
</div>
<div className="form-group">
<div className="col-md-12">
<input type="submit" value="Submit" className="btn btn-sm btn-block btn-primary"/>
</div>
</div>
</form>
);
}
}
export default ContactForm
The section of code I have problems with is in handleSubmit function.
Thanks for help in advance and a happy new year to all.
I have moved the validity check to handleChange function and it is now working as intended.
Thanks a lot!

Categories