How to Edit a form in React by using functional components - reactjs

I am working on a React project, In my project I have a form, In that form I fetch data by Id
From the backend, Now I am trying to do put method. But I have no idea how doing it so please me
How to send edited data to backend using the put method.
This is my code Editstudentdetails.js
import React, { useState, useEffect } from 'react';
import './Editstudentdetails.css';
import axios from 'axios';
import { withRouter } from 'react-router-dom'
function Editstudentdetails(props) {
const [getStudentDataById, setStudentDataById] = useState([])
const [editStudentDataById, latestEdit] = useState({ name:'', position: '', location: '', salary: '', email: '', password: '' })
const id = props.match.params.id
console.log(id)
useEffect(() => {
const getDataById = async () => {
try {
const result = await axios.get(`http://localhost:7500/api/registration/${id}`)
setStudentDataById(result.data)
console.log(result.data)
} catch (error) {
console.log(error)
}
}
getDataById()
}, [])
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, getStudentDataById, { [name]: value });
setStudentDataById(newData);
const latestData = Object.assign({}, editStudentDataById, { [name]: value })
latestEdit(latestData)
}
const handleSubmit = async e => {
e.preventDefault();
console.warn(editStudentDataById)
const editDataById = async () => {
try {
const response = await axios.put(`http://http://localhost:7500/api/registration/${id}`, editStudentDataById)
latestEdit(response.data)
console.warn(response.data)
} catch (error) {
console.warn(error)
}
}
editDataById()
}
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input type="text" name='name' value={getStudentDataById.name} onChange={handleChange} className="form-control" id="name"></input>
</div>
<div className="form-group">
<label htmlFor="position">Position</label>
<input type="text" name='position' value={getStudentDataById.position} onChange={handleChange} className="form-control" id="position"></input>
</div>
<div className="form-group">
<label htmlFor="location">Location</label>
<input type="text" name='location' value={getStudentDataById.location} onChange={handleChange} className="form-control" id="location"></input>
</div>
<div className="form-group">
<label htmlFor="salary">Salary</label>
<input type="number" name='salary' value={getStudentDataById.salary} onChange={handleChange} className="form-control" id="salary"></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" name='email' onChange={handleChange} value={getStudentDataById.email} className="form-control" id="email"></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" name='password' onChange={handleChange} value={getStudentDataById.password} className="form-control" id="password"></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default withRouter(Editstudentdetails)
If you feel I am not clear with my doubt please put a comment Thank you

Please follow this example. It works perfectly.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
function EditStudentDetails() {
const [post, setPost] = useState({});
const id = 1;
const handleChange = ({target}) => {
const {name, value} = target;
setPost({...post, [name]: value});
console.log(post);
};
const handleSubmit = async e => {
e.preventDefault();
const editDataById = async () => {
try {
const response = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PUT',
body: JSON.stringify({
id: id,
title: post.title,
body: post.body,
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
};
editDataById();
};
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Title</label>
<input type="text" name='title' value={post.title} onChange={handleChange}
className="form-control" id="title"/>
</div>
<div className="form-group">
<label htmlFor="position">Body</label>
<input type="text" name='body' value={post.body}
onChange={handleChange} className="form-control" id="body"/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default EditStudentDetails;

Related

Why my page is not redirecting to login page after successful registration in React?

Here, props.history.push("/login"); is not working
Other all things are Working
Can anyone Help?
import React, { useState } from 'react'
import { Link } from "react-router-dom";
import axios from "axios";
const Register = (props) => {
const [data, setData] = useState({
name: "",
email: "",
password: ""
})
const { name, email, password } = data;
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post(
"/auth/register", { name, email, password }, {
headers: {
"Content-Type": "application/json",
},
}
);
props.history.push("/login");
} catch (err) {
console.log(err);
}
};
return (
<form>
<h3>Create an account</h3>
<div className="mb-3">
<label>Name</label>
<input
type="text"
className="form-control"
placeholder="First name"
name="name"
value={name}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Email</label>
<input
type="email"
className="form-control"
placeholder="Enter email"
name="email"
value={email}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Enter Password"
name="password"
value={password}
onChange={handleChange}
/>
</div>
<div className="d-grid">
<button type="submit" className="btn btn-primary" onClick={handleSubmit}>
Register
</button>
</div>
<p className="forgot-password text-right">
Already registered? <Link to="/login">Login</Link>
</p>
</form>
);
}
export default Register
You have to try using this
import { useHistory } from "react-router-dom";
In function components
let history = useHistory();
After successfully register
history.push("/login");
Now it works
import React, { useState } from 'react'
import { Link } from "react-router-dom";
import axios from "axios";
import { useNavigate } from 'react-router-dom';
const Register = (props) => {
const [data, setData] = useState({
name: "",
email: "",
password: ""
})
const { name, email, password } = data;
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
let navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post(
"/auth/register", { name, email, password }, {
headers: {
"Content-Type": "application/json",
},
}
);
navigate("/login");
} catch (err) {
console.log(err);
}
};
return (
<form>
<h3>Create an account</h3>
<div className="mb-3">
<label>Name</label>
<input
type="text"
className="form-control"
placeholder="First name"
name="name"
value={name}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Email</label>
<input
type="email"
className="form-control"
placeholder="Enter email"
name="email"
value={email}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Enter Password"
name="password"
value={password}
onChange={handleChange}
/>
</div>
<div className="d-grid">
<button type="submit" className="btn btn-primary" onClick={handleSubmit}>
Register
</button>
</div>
<p className="forgot-password text-right">
Already registered? <Link to="/login">Login</Link>
</p>
</form>
);
}
export default Register

React, functional component. Input focus is thrown off when a character is entered

I'm new in react. The problem is this - when I enter data into the input, my focus is reset. I understand that it happens due to changeHandler. But I don't understand how to change it. I've seen similar problems, but they are all related to class components. I would like to implement the solution exactly in a functional component, not using classes.
import React, { useContext, useEffect, useState } from 'react'
import { AuthContext } from '../context/AuthContext'
import axios from 'axios';
import { render } from '#testing-library/react';
export const AuthPage = () => {
const auth = useContext(AuthContext)
const [typeOfForm, setTypeOfForm] = useState('login')
const [form, setForm] = useState({
email: '', password: ''
})
const loginHandler = async () => {
try {
var config = {
headers: { 'Access-Control-Allow-Origin': '*' }
};
axios.post('http://localhost:5000/api/login', { ...form }, { headers: { 'Authorization': `Bearer ${auth.token}` } })
.then(response => response.data.map(part => { auth.login(part.token, part.userId); console.log(part) }))
.catch(function (error) {
console.log(error);
});
} catch (e) { }
}
const registerHandler = async () => {
try {
var config = {
headers: { 'Authorization': `Bearer ${auth.token}` }
};
axios.post('http://localhost:5000/api/register', { ...form })
.then(response => response.data.map(part => { auth.login(part.token, part.userId); console.log(part) }))
.catch(function (error) {
console.log(error);
});
} catch (e) { }
}
const changeHandler = event => {
setForm({ ...form, [event.target.name]: event.target.value })
}
return (
<div className="App" key="editor2">
<div className="logreg-bg"></div>
<a href="/">
<h1 id="logreg-logo">Animal Assistance <br /> <span id="logreg-logo-down">save nature togehter</span></h1>
</a>
{typeOfForm == 'login' ? <LoginForm /> : <RegisterForm />}
<h1 id="logreg-logo2"> Created by: <br /> <span id="logreg-logo-down2">PTN</span></h1>
</div>
);
function LoginForm() {
return (
<div id="logreg-form-container">
<h1 id="form-header">Log in</h1>
<div id="label-logreg-input">
<div className="logreg-labels">
<label htmlFor="email" id="login-label">Email</label>
</div>
<input
placeholder="Email"
type="text"
id="login"
name="email"
value={form.email}
onChange={changeHandler}
required />
</div>
<div id="label-logreg-input">
<div className="logreg-labels">
<label htmlFor="password" id="password-label">Password</label>
</div>
<input
placeholder="Password"
type="password"
id="password"
name="password"
value={form.password}
onChange={changeHandler}
required />
<div id="logreg-button-container">
<button
onClick={registerHandler}
id="logreg-form-button"
>Login</button>
</div>
</div>
<div id="go-to-else-container">
<a id="go-to-else"
onClick={() => setTypeOfForm('register')}>Register</a>
</div>
</div>
)
}
function RegisterForm() {
return (
<div id="logreg-form-container">
<h1 id="form-header">Register</h1>
<div id="label-logreg-input">
<div className="logreg-labels">
<label htmlFor="email" id="login-label">Email</label>
</div>
<input
placeholder="Введите email"
value={form.email}
onChange={changeHandler}
type="text"
id="login"
name="email"
required />
</div>
<div id="label-logreg-input">
<div className="logreg-labels">
<label htmlFor="password" id="password-label">Password</label>
</div>
<input
placeholder="Введите пароль"
value={form.password}
onChange={changeHandler}
type="password"
id="password"
name="password"
required />
<div id="logreg-button-container">
<button
type="submit"
id="logreg-form-button"
>Register</button>
</div>
</div>
<div id="go-to-else-container">
<a id="go-to-else"
onClick={() => setTypeOfForm('login')}>Login</a>
</div>
</div>
)
}
}
export default AuthPage;
Problems:
Focus is being lost because currently, input changes the state of a higher level component. The automatically causes a re-rendering of its child (the login or sign up form), because it is being completely defined again.
This causes an automatic re-render since React and browser think it
got a COMPLETELY NEW component.
Solutions:
Move the form state, and changeHandler function, to each respective form component, and allow them to manage their state independently. That way, this won't happen.
Recommended Approach:
If you want to form and changleHandler in a higher level component, then define the child components (Login and Sign Up) separately from AuthPage. Then just pass them the form state, and changeHandler function, as props.
Below if the 2nd approach being implemented
Since you would define both components separately, ensure you pass all the variables and functions in AuthPage, that are needed in each form, as props/parameters too. This is for functional purposes, and because it is best practice for maintenance on react apps.
Let me know if it helps :)
import React, { useContext, useEffect, useState } from 'react'
import { AuthContext } from '../context/AuthContext'
import axios from 'axios';
import { render } from '#testing-library/react';
function LoginForm({form, changeFormType, changeHandler, registerHandler}) {
return (
<div id="logreg-form-container">
<h1 id="form-header">Log in</h1>
<div id="label-logreg-input">
<div className="logreg-labels">
<label htmlFor="email" id="login-label">Email</label>
</div>
<input
placeholder="Email"
type="text"
id="login"
name="email"
value={form.email}
onChange={changeHandler}
required />
</div>
<div id="label-logreg-input">
<div className="logreg-labels">
<label htmlFor="password" id="password-label">Password</label>
</div>
<input
placeholder="Password"
type="password"
id="password"
name="password"
value={form.password}
onChange={changeHandler}
required />
<div id="logreg-button-container">
<button
onClick={registerHandler}
id="logreg-form-button"
>Login</button>
</div>
</div>
<div id="go-to-else-container">
<a id="go-to-else"
onClick={changeFormType}>Register</a>
</div>
</div>
)
}
function RegisterForm({form, changeFormType, changeHandler}) {
return (
<div id="logreg-form-container">
<h1 id="form-header">Register</h1>
<div id="label-logreg-input">
<div className="logreg-labels">
<label htmlFor="email" id="login-label">Email</label>
</div>
<input
placeholder="Введите email"
value={form.email}
onChange={changeHandler}
type="text"
id="login"
name="email"
required />
</div>
<div id="label-logreg-input">
<div className="logreg-labels">
<label htmlFor="password" id="password-label">Password</label>
</div>
<input
placeholder="Введите пароль"
value={form.password}
onChange={changeHandler}
type="password"
id="password"
name="password"
required />
<div id="logreg-button-container">
<button
type="submit"
id="logreg-form-button"
>Register</button>
</div>
</div>
<div id="go-to-else-container">
<a id="go-to-else"
onClick={changeFormType}>Login</a>
</div>
</div>
)
}
const AuthPage = () => {
const auth = useContext(AuthContext)
const [typeOfForm, setTypeOfForm] = useState('login')
const [form, setForm] = useState({
email: '', password: ''
})
const loginHandler = async () => {
try {
var config = {
headers: { 'Access-Control-Allow-Origin': '*' }
};
axios.post('http://localhost:5000/api/login', { ...form }, { headers: { 'Authorization': `Bearer ${auth.token}` } })
.then(response => response.data.map(part => { auth.login(part.token, part.userId); console.log(part) }))
.catch(function (error) {
console.log(error);
});
} catch (e) { }
}
const registerHandler = async () => {
try {
var config = {
headers: { 'Authorization': `Bearer ${auth.token}` }
};
axios.post('http://localhost:5000/api/register', { ...form })
.then(response => response.data.map(part => { auth.login(part.token, part.userId); console.log(part) }))
.catch(function (error) {
console.log(error);
});
} catch (e) { }
}
const changeHandler = event => {
setForm({ ...form, [event.target.name]: event.target.value })
}
const changeFormType = event =>{
//add your condition based of e.target
setTypeOfForm('login')
//add your condition based of e.target
setTypeOfForm('register')
}
return (
<div className="App" key="editor2">
<div className="logreg-bg"></div>
<a href="/">
<h1 id="logreg-logo">Animal Assistance <br /> <span id="logreg-logo-down">save nature togehter</span></h1>
</a>
{typeOfForm == 'login' ? <LoginForm
changeHandler={changeHandler}
form={form}
changeFormType={changeFormType}
registerHandler={registerHandler}/>
: <RegisterForm
changeHandler={changeHandler}
form={form}
changeFormType={changeFormType}
/>}
<h1 id="logreg-logo2"> Created by: <br /> <span id="logreg-logo-down2">PTN</span></h1>
</div>
);
}
export default AuthPage;

put method not working with react axios api method

I have this api running on my localhost, using drf. I defined a put method to use to update an object. When i do this in the backend it works, everything gets updated, but when i do it in the frontend nothing gets updated but i get a 200 OK status code. How can i make it work?
Here is my react code:
import React, { useState, useEffect } from 'react';
import { useHistory, useParams } from 'react-router';
import axios from 'axios';
const EkoEditPage = () => {
const [disco, setDisco] = useState("")
const [feederSource33kv, setFeederSource33kv] = useState("")
const [injectionSubstation, setInjectioSubstation] = useState("")
const [feederName, setFeederName] = useState("")
const [band, setBand ] = useState("")
const [status, setStatus] = useState("")
const history = useHistory();
const { id } = useParams();
const loadEkoMyto = async () => {
const { data } = await axios.get(`http://127.0.0.1:8000/main/view/${id}`);
setDisco(data.dicso)
setFeederSource33kv(data.feeder_source_33kv)
setInjectioSubstation(data.injection_substation)
setFeederName(data.feeder_name )
setBand(data.band)
setStatus(data.status)
}
const updateEkoMyto = async () => {
let formField = new FormData()
formField.append('disco', disco)
formField.append('feeder_source_33kv', feederSource33kv)
formField.append('injecttion_substation', injectionSubstation)
formField.append('feeder_name',feederName)
formField.append('band', band)
formField.append('status', status)
await axios({
method: 'PUT',
url: `http://127.0.0.1:8000/main/edit/${id}`,
data: formField
}).then(response => {
console.log(response.data)
})
}
useEffect (() => {
loadEkoMyto()
}, [])
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h2 className="text-center mb-4">Update A Student</h2>
<div className="form-group">
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
name="disco"
value={disco}
onChange={(e) => setDisco(e.target.value)}
/>
</div>
<div className="form-group">
<input
className="form-control form-control-lg"
placeholder="Enter Your E-mail Address"
name="feeder_source_33kv"
value={feederSource33kv}
onChange={(e) => setFeederSource33kv(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Phone Number"
name="injection_substation"
value={injectionSubstation}
onChange={(e) => setInjectioSubstation(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your address Name"
name="address"
value={feederName}
onChange={(e) => setFeederName(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
name="address"
value={band}
onChange={(e) => setBand(e.target.value)}
/>
</div>
<select name="status" onChange={(e) => setStatus(e.target.value)}>
<option value={status}>Yes</option>
<option value={status}>No</option>
</select>
<button className="btn btn-primary btn-block" onClick={updateEkoMyto}>Update Eko</button>
</div>
</div>
);
};
export default EkoEditPage;
}

Is it possible Preload a form with Firestore values?

I have a form that uploads its values to the Firestore database, and would like to use the same component for updating the values, so the question might really be - how to load initial state according to a conditional whether the props are passed?
The form
import Servis from "./funkc/servisni";
import React, { useState } from "react";
export default function ContactUpdate(props) {
//
console.log(props.item);
//
const initialState = {
id: props.item.id,
ime: props.item.Ime,
prezime: props.item.Prezime,
imeError: "",
prezimeError: "",
date: props.item.Datum,
kontakt: props.item.Kontakt,
kontaktError: "",
published: true,
};
const [theItem, setTheItem] = useState(initialState);
const [imeError, setImeError] = useState();
const [prezimeError, setPrezimeError] = useState();
const [message, setMessage] = useState();
const { item } = props;
if (theItem.id !== item.id) {
setTheItem(item);
}
const handleInputChange = (event) => {
const { name, value } = event.target;
setTheItem({ ...theItem, [name]: value });
};
const updatePublished = (status) => {
Servis.update(theItem.id0, { published: status })
.then(() => {
setTheItem({ ...theItem, published: status });
setMessage("The status was updated successfully!");
})
.catch((e) => {
console.log(e);
});
};
const updateItem = () => {
let data = {
Ime: theItem.ime,
Prezime: theItem.prezime,
Kontakt: theItem.kontakt,
Datum: theItem.date,
published: true,
};
Servis.update(theItem.id, data)
.then(() => {
setMessage("The tutorial was updated successfully!");
})
.catch((e) => {
console.log(e);
});
};
const deleteItem = () => {
Servis.remove(theItem.id)
.then(() => {
props.refreshList();
})
.catch((e) => {
console.log(e);
});
};
const validate = () => {
let imeError = "";
let kontaktError = "";
if (!theItem.ime) {
imeError = "obavezan unos imena!";
}
if (!theItem.kontakt) {
imeError = "obavezan unos kontakta!";
}
if (kontaktError || imeError) {
this.setState({ kontaktError, imeError });
return false;
}
return true;
};
return (
<div className="container">
{theItem ? (
<div className="edit-form">
<h4>Kontakt</h4>
<form>
<div className="form-group">
<label htmlFor="ime">Ime</label>
<input
type="text"
className="form-control"
// id="title"
name="ime"
value={theItem.Ime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Prezime">Prezime</label>
<input
type="text"
className="form-control"
// id="description"
name="Prezime"
value={theItem.Prezime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Datum">Datum</label>
<input
type="text"
className="form-control"
// id="description"
name="Datum"
value={theItem.Datum}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Kontakt">Kontakt</label>
<input
type="text"
className="form-control"
// id="description"
name="Kontakt"
value={theItem.Kontakt}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
{theItem.published ? "Published" : "Pending"}
</div>
</form>
{theItem.published ? (
<button onClick={() => updatePublished(false)}>UnPublish</button>
) : (
<button onClick={() => updatePublished(true)}>Publish</button>
)}
<button onClick={deleteItem}>Delete</button>
<button type="submit" onClick={updateItem}>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Please click on a Tutorial...</p>
</div>
)}{" "}
</div>
);
}
The component passing the props:
import React, { useState, useEffect } from "react";
import firebase from "./firebase";
import { Link } from "react-router-dom";
export default function FireDetail({ match }) {
console.log(match);
console.log(match.params.id);
const [item, setItem] = useState([]);
const [loading, setLoading] = useState();
const getIt = () => {
setLoading(true);
const docRef = firebase
.firestore()
.collection("polja")
.doc(match.params.id)
.get()
.then((doc) => {
setItem(doc.data());
});
//
console.log(docRef);
//
// const docRef = firebase.firestore().collection("polja").doc("documentId")
//
setLoading(false);
};
useEffect(() => {
getIt();
}, [match]);
if (loading) {
return <h3>samo malo...</h3>;
}
return (
<div className="container">
<div>
{console.log("item: ", item)}
Kontakt: tip - email
<p> {item.Kontakt}</p>
</div>
<div>
<p>Datum rodjenja: {item.Datum}</p>
{item.Prezime} {item.Ime}
</div>
<Link to={`/kontakt/update/${item.id}`}> ajd </Link>
</div>
);
}
Or you might have an alternative idea on how to solve the problem?
indeed it is
export default function ContactUpdate(props) {
const initialState = {
ime: props.item.Ime,
prezime: props.item.Prezime,
datum: props.item.Datum,
kontakt: props.item.Kontakt,
id: props.Id,
};
const [theItem, setTheItem] = useState();
const [message, setMessage] = useState();
useEffect(() => {
setTheItem(props.item);
}, []);
const handleInputChange = (event) => {
const { name, value } = event.target;
setTheItem({ ...theItem, [name]: value });
console.log(theItem);
};
const updateItem = (theItem) => {
let data = {
Ime: theItem.Ime,
Prezime: theItem.Prezime,
Kontakt: theItem.Kontakt,
Datum: theItem.Datum,
};
console.log(updateItem());
Servis.update(theItem.id, data)
.then(() => {
setMessage("Uspjesno ste izmijenili unos!");
})
.catch((e) => {
console.log(e);
});
};
const deleteItem = () => {
Servis.remove(theItem.id).catch((e) => {
console.log(e);
});
};
return (
<div className="container">
{console.log(("theItem", props, theItem))}
{theItem ? (
<div className="edit-form">
<h4>Kontakt</h4>
<form>
<div className="form-group">
<label htmlFor="ime">Ime</label>
<input
type="text"
className="form-control"
name="Ime"
value={theItem.Ime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="prezime">Prezime</label>
<input
type="text"
className="form-control"
name="Prezime"
value={theItem.Prezime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="datum">Datum</label>
<input
type="text"
className="form-control"
name="Datum"
value={theItem.Datum}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="kontakt">Kontakt</label>
<input
type="text"
className="form-control"
name="Kontakt"
value={theItem.Kontakt}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
</div>
</form>
<button onClick={deleteItem}>Delete</button>
<button type="submit" onClick={updateItem}>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Odaberi jedan broj...</p>
</div>
)}{" "}
</div>
);
}

the state inside hooks are not updated for first time on form submit in react

I was trying to implement contactUS form in react using hooks.Contact us form is placed inside hooks.When I first submit the form the state in hooks are not updated ,when I click 2nd time states are set .and I am returning state to class component there api call are made.
//contactushook.js
import React, { useState } from 'react';
const ContactUshook = ({ parentCallBack }) => {
const [data, setData] = useState([]);
const handleSubmit = (event) => {
event.preventDefault();
setData({ name: document.getElementById('name').value, email: document.getElementById('email').value, message: document.getElementById('message').value });
console.log(data);
parentCallBack(data);
}
return <React.Fragment>
<div className="form-holder">
<form onSubmit={handleSubmit}>
<div>
<input id="name" type="text" placeholder="enter the name"></input>
</div>
<div>
<input id="email" type="email" placeholder="enter the email"></input>
</div>
<div>
<textarea id="message" placeholder="Type message here"></textarea>
</div>
<button type="submit" >Submit</button>
</form>
</div>
</React.Fragment >
}
export default ContactUshook;
//contactus.js
import React, { Component } from 'react';
import ContactUshook from './hooks/contactushook';
import '../contactUs/contactus.css';
class ContactComponent extends Component {
onSubmit = (data) => {
console.log('in onsubmit');
console.log(data);
}
render() {
return (
<div>
<h4>hook</h4>
<ContactUshook parentCallBack={this.onSubmit}></ContactUshook>
</div>
);
}
}
export default ContactComponent;
Stop using document queries and start using state instead!
Your ContactUshook component should look like this:
const ContactUshook = ({ parentCallBack }) => {
const [data, setData] = useState({ name: '', email: '', message: '' });
const handleSubmit = () => {
event.preventDefault();
parentCallBack(data);
}
const handleChange = (event, field) => {
const newData = { ...data };
newData[field] = event.target.value;
setData(newData);
}
return (
<div className="form-holder">
<form onSubmit={handleSubmit}>
<div>
<input
id="name"
type="text"
value={data.name}
placeholder="enter the name"
onChange={(e) => handleChange(e,'name')} />
</div>
<div>
<input
id="email"
type="email"
value={data.email}
placeholder="enter the email"
onChange={(e) => handleChange(e,'email')} />
</div>
<div>
<textarea
id="message"
value={data.message}
placeholder="Type message here"
onChange={(e) => handleChange(e,'message')} />
</div>
<button type="submit" >Submit</button>
</form>
</div>
);
}

Resources