I am making an application and I have an error that I do not understand very well. Apparently, it is in the hook that I am using to make protected pages. I share the error and the code below.
Unhandled Runtime Error Error: Too many re-renders. React limits the
number of renders to prevent an infinite loop.
import firebase from "firebase";
const firebaseConfig = {
apiKey: "Key",
authDomain: "Domain",
databaseURL: "URL",
projectId: "Id",
storageBucket: "Bucket",
messagingSenderId: "SenderId",
appId: "appId",
measurementId: "measurementId",
};
// Initialize Firebase
!firebase.apps.length && firebase.initializeApp(firebaseConfig);
export const database = firebase.database().ref();
const mapUserFromFirebaseAuthToUser = (user) => {
const { displayName, email, uid } = user;
return {
userName: displayName,
email,
uid,
};
};
export const onAuthStateChanged = (onChange) => {
const emailProvider = new firebase.auth();
return emailProvider.onAuthStateChanged((user) => {
const normalizedUser = user ? mapUserFromFirebaseAuthToUser(user) : null;
onChange(normalizedUser);
});
};
export const loginUser = ({ email, password }) => {
const emailProvider = new firebase.auth();
return emailProvider.signInWithEmailAndPassword(email, password);
};
export const singUp = () => {
const emailProvider = new firebase.auth();
return emailProvider.signOut();
};
the page where the application breaks
import { useState, useEffect } from "react";
import styles from "styles/Countries.module.css";
import useUser, { USER_STATES } from "hooks/useUser";
import NavbarMenu from "components/navBar";
import Footer from "components/footer";
import { database } from "utils/firebase";
import {
Table,
Button,
Container,
Modal,
ModalBody,
ModalHeader,
ModalFooter,
FormGroup,
} from "reactstrap";
export default function Countries() {
const user = useUser();
const [timeLine, setTimeLine] = useState([]);
const [isOpenModalAdd, setIsOpenModalAdd] = useState(false);
const [isOpenModalEdit, setIsOpenModalEdit] = useState(false);
const [name, setName] = useState("");
const [currency, setCurrency] = useState("");
const [base, setBase] = useState("");
const [km, setKm] = useState("");
const [minute, setMinute] = useState("");
const [code, setCode] = useState("");
const [country, setCountry] = useState({
name: "",
currency_code: "",
base_fare: "",
per_km: "",
per_minute: "",
});
useEffect(() => {
database.child("Admin/Country").on("value", (snapshot) => {
setTimeLine(snapshot.val());
});
}, []);
const selectCountry = (data, id, status) => {
setCountry(data);
setCode(id);
status === "edit" && setIsOpenModalEdit(true);
};
const editCountry = () => {
database.child("Admin/Country/" + code).set(country);
resetModalAdd();
setIsOpenModalEdit(false);
};
const saveCountry = () => {
const MapCountry = {
name: name,
currency_code: currency,
base_fare: base,
per_km: km,
per_minute: minute,
};
database.child("Admin/Country/" + code).set(MapCountry);
resetModalAdd();
setIsOpenModalAdd(false);
};
const resetModalAdd = () => {
setName("");
setCurrency("");
setBase("");
setKm("");
setMinute("");
setCode("");
};
const openModalAdd = () => {
setIsOpenModalAdd(true);
};
const closeModalAdd = () => {
setIsOpenModalAdd(false);
};
const handleChangeName = (event) => {
const { value } = event.target;
setName(value);
let string = value;
let part = string.split("");
if (part.length === 2) {
let code = part[0].toUpperCase() + part[1].toUpperCase();
setCode(code);
}
};
const handleChangeData = (event) => {
const { value } = event.target;
setCountry(value);
};
const handleChangeCurrency = (event) => {
const { value } = event.target;
setCurrency(value);
};
const handleChangeBase = (event) => {
const { value } = event.target;
setBase(value);
};
const handleChangeKm = (event) => {
const { value } = event.target;
setKm(value);
};
const handleChangeMinute = (event) => {
const { value } = event.target;
setMinute(value);
};
return user ? (
<>
<div className={styles.container}>
<div className={styles.principalMenu}>
<NavbarMenu>
<div className={styles.titleHeader}>
<div className={styles.title}>Administration System</div>
<div className={styles.subtitle}>User: {user.userName}</div>
</div>
</NavbarMenu>
</div>
<div>
<h3>Country</h3>
</div>
<Container>
<Button color="primary" onClick={openModalAdd}>
New Country
</Button>
<Table>
<thead>
<tr>
<th>Name</th>
<th>Currency Code</th>
<th>Base Fare</th>
<th>Per Km</th>
<th>Per Minute</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{Object.keys(timeLine).map((i) => {
return (
<tr key={i}>
<td>{timeLine[i].name}</td>
<td>{timeLine[i].currency_code}</td>
<td>{timeLine[i].base_fare}</td>
<td>{timeLine[i].per_km}</td>
<td>{timeLine[i].per_minute}</td>
<td>
<Button
color="primary"
onClick={selectCountry(timeLine[i], i, "edit")}
>
Editar
</Button>
{" "}
<Button color="danger">Eliminar</Button>
</td>
</tr>
);
})}
</tbody>
</Table>
<Modal isOpen={isOpenModalAdd}>
<ModalHeader>Insertar Registro</ModalHeader>
<ModalBody>
<div className="form-group">
<label>Name: </label>
<br />
<input
type="text"
className="form-control"
value={name}
onChange={handleChangeName}
/>
<label>Currency Code: </label>
<br />
<input
type="text"
className="form-control"
value={currency}
onChange={handleChangeCurrency}
/>
<label>Base Fare: </label>
<br />
<input
type="text"
className="form-control"
value={base}
onChange={handleChangeBase}
/>
<label>Per Km: </label>
<br />
<input
type="text"
className="form-control"
value={km}
onChange={handleChangeKm}
/>
<label>Per Minute: </label>
<br />
<input
type="text"
className="form-control"
value={minute}
onChange={handleChangeMinute}
/>
</div>
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={saveCountry}>
Guardar
</Button>
{" "}
<Button color="danger" onClick={closeModalAdd}>
Cancelar
</Button>
</ModalFooter>
</Modal>
<Modal isOpen={isOpenModalEdit}>
<ModalHeader>Editar Registro</ModalHeader>
<ModalBody>
<div className="form-group">
<label>Name: </label>
<br />
<input
type="text"
className="form-control"
name="name"
value={country.name}
onChange={handleChangeData}
/>
<label>Currency Code: </label>
<br />
<input
type="text"
className="form-control"
name="currency_code"
value={country.currency_code}
onChange={handleChangeData}
/>
<label>Base Fare: </label>
<br />
<input
type="text"
className="form-control"
name="base_fare"
value={country.base_fare}
onChange={handleChangeData}
/>
<label>Per Km: </label>
<br />
<input
type="text"
className="form-control"
name="per_km"
value={country.per_km}
onChange={handleChangeData}
/>
<label>Per Minute: </label>
<br />
<input
type="text"
className="form-control"
name="per_minute"
value={country.per_minute}
onChange={handleChangeData}
/>
</div>
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={editCountry}>
Guardar
</Button>
{" "}
<Button color="danger" onClick={setIsOpenModalEdit(false)}>
Cancelar
</Button>
</ModalFooter>
</Modal>
</Container>
<Footer />
</div>
</>
) : user === USER_STATES.NOT_KNOWN ? (
<>
<div className={styles.container}>
<h1>Loading...</h1>
</div>
</>
) : (
<>
<div className={styles.container}>
<h1>Not authorized</h1>
</div>
</>
);
}
The hooks used for protected pages:
import { Router } from "next/router";
import { useState, useEffect } from "react";
import { useRouter } from "next/router";
import { onAuthStateChanged } from "utils/firebase";
export const USER_STATES = {
NOT_LOGGED: null,
NOT_KNOWN: undefined,
};
export default function useUser() {
const [user, setUser] = useState(USER_STATES.NOT_KNOWN);
const router = useRouter();
useEffect(() => {
onAuthStateChanged(setUser);
}, []);
useEffect(() => {
user === USER_STATES.NOT_LOGGED && router.push("/login");
}, [user]);
return user;
}
I hope this is enough to give me a hand. I have already tried to solve but the truth is I do not find the problem.
The logic in these lines is not correct:
useEffect(() => {
onAuthStateChanged(setUser);
}, []);
useEffect(() => {
user === USER_STATES.NOT_LOGGED && router.push("/login");
}, [user]);
I understand the first useEffect is used to update the state,
but the second useEffect watches this state and returning boolean?
Instead of user === USER_STATES.NOT_LOGGED && router.push("/login");, it should be:
if (USER_STATES.NOT_LOGGED) { router.push("/login"); }
Related
I'm working on a Sign Up form using React, I'm having troubles with password field, for some reason I can't type nothing in there, it is just like in read only mode, this is the code of my component:
import React, { useState, useRef } from "react";
import Modal from "../UI/Modal";
import classes from "./Login.module.css";
import Input from "../UI/Input/Input";
const Signup = (props) => {
const [firstNameValue, setFirstNameValue] = useState('');
const [lastNameValue, setLastNameValue] = useState('');
const [emailClientValue, setEmailClientValue] = useState('');
const [passwordClientValue, setPasswordClientValue] = useState('12345');
const [isCanceling, setIsCanceling] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [didSave, setDidSave] = useState(false);
const [isErrorOnSave, setIsErrorOnSave] = useState(false);
//const cartCtx = useContext(CartContext);
const firstNameValueHandler = (event) => {
setFirstNameValue(event.target.value);
}
const lastNameValueHandler = (event) => {
setLastNameValue(event.target.value);
}
const emailClientValueHandler = (event) => {
setEmailClientValue(event.target.value);
}
const passwordClientValueHandler = (event) => {
setPasswordClientValue(event.target.value);
}
const errorOnSignupHandler = () => {
setIsErrorOnSave(true);
};
const signupHandler = async () => {
setIsSaving(true);
const enteredFirstname = firstNameValue;
const enteredLastname = lastNameValue;
const enteredEmail = emailClientValue;
const enteredPassword = passwordClientValue;
const newClientData = {
firstname: enteredFirstname,
lastname: enteredLastname,
email: enteredEmail,
password: enteredPassword,
};
console.log(newClientData);
const response = await fetch("http://localhost:3000/clients", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newClientData),
});
if (!response.ok) {
errorOnSignupHandler();
} else {
setIsSaving(false);
setIsCanceling(false);
setDidSave(true);
//cartCtx.clearCart();
}
};
const isSavingModalContent = <p>Saving new user...</p>;
/* incluir transaccion para verificar si es exitoso o hubo algun error */
const errorOnSavingModalContent = (
<React.Fragment>
<p>The user account could not be created. Please try again later</p>
<div className={classes.actions}>
<button className={classes.button} onClick={props.onClose}>
Close
</button>
</div>
</React.Fragment>
);
const didSaveModalContent = (
<React.Fragment>
<p>User account created, welcome!</p>
<div className={classes.actions}>
<button className={classes.button} onClick={props.onClose}>
Close
</button>
</div>
</React.Fragment>
);
const SignupButtons = (
<React.Fragment>
<button className={classes["button--alt"]} onClick={signupHandler}>
Sign-Up
</button>
<button className={classes["button--alt"]} onClick={props.onClose}>
Close
</button>
</React.Fragment>
);
const modalActions = (
<div className={classes.actions}>{!isCanceling ? SignupButtons : ""}</div>
);
const SignupModalContent = (
<React.Fragment>
<Input
onChange={firstNameValueHandler}
id="firstname"
label="First Name"
type="text"
value={firstNameValue}
//isValid={emailIsValid}
//value={emailState.value}
//onChange={emailChangeHandler}
//onBlur={validateEmailHandler}
/>
<Input
onChange={lastNameValueHandler}
id="lastname"
label="Last Name"
type="text"
value={lastNameValue}
//isValid={emailIsValid}
//value={emailState.value}
//onChange={emailChangeHandler}
//onBlur={validateEmailHandler}
/>
<Input
onChange={emailClientValueHandler}
id="email"
label="E-Mail"
type="email"
autodata="off"
value={emailClientValue}
//isValid={emailIsValid}
//value={emailState.value}
//onChange={emailChangeHandler}
//onBlur={validateEmailHandler}
/>
<Input
onchange={passwordClientValueHandler}
id="paswword"
label="Password"
type="password"
autodata="new-password"
value={passwordClientValue}
//isValid={passwordIsValid}
//value={passwordState.value}
//onChange={passwordChangeHandler}
//onBlur={validatePasswordHandler}
/>
<Input
//ref={passwordInputRef}
id="paswword2"
label="Confirm-Password"
type="password"
autodata="new-password"
//isValid={passwordIsValid}
//value={passwordState.value}
//onChange={passwordChangeHandler}
//onBlur={validatePasswordHandler}
/>
{modalActions}
</React.Fragment>
);
return (
<Modal onClose={props.onClose}>
{!isCanceling && !isSaving && !isErrorOnSave && !didSave && SignupModalContent}
{isSaving && isSavingModalContent}
{isErrorOnSave && errorOnSavingModalContent}
{!isSaving && didSave && didSaveModalContent}
</Modal>
);
};
export default Signup;
The Input.js component is this:
import React from 'react';
import classes from './Input.module.css';
const Input = React.forwardRef((props, ref) => {
return(
<div className={classes.input}>
<label htmlFor={props.id}>{props.label}</label>
<input ref={ref} {...props}/>
</div>
);
});
export default Input;
I found the problem is in this line:
value={passwordClientValue}
If I remove it I can type in the textbox but I can't fetch the data, also I tried to use a standard html <input type="password> but still can't type in there.
My question: what else do I need to do in order to type in the textbox and get the data?
Thanks a lot.
in this, I have uploaded the image but I want to preview the image before uploading it how can I do that in react js.can any one give me the help by giving the answer or by giving me a sample program I am posting my code can anyone help me with it I am stuck with it for a long time. The code is given below:
const { REACT_APP_SERVER_URL } = process.env;
function UserForm(props) {
const {
register,
handleSubmit,
formState: { errors },
setValue,
} = useForm({ defaultValues: props.item });
const [items, setItems] = useState([]);
const getRoleData = () => {
const baseURL = `${REACT_APP_SERVER_URL}/apis/role/all`;
axios.get(baseURL).then((response) => {
setItems(response.data.data);
});
};
useEffect(() => {
getRoleData();
}, []);
const uploadPhoto = (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onloadend = () => {
setValue('photo', reader.result);
};
reader.readAsDataURL(file);
}
return (
<form className="userForm">
<div className="form-group">
<label htmlFor="photo">Profile Photo</label>
<input
type="file"
accept=".png, .jpg, .jpeg"
className="form-control"
name="photo"
onChange={(e) => uploadPhoto(e)}
placeholder="Enter your office photo "
// {...register("photo")}
/>
{errors.photo && (
<p className="text-danger">Photo is required</p>
)}
</div>
<div className="form-group mt-4">
{!props.viewItem && props.view && (
<Button
onClick={handleSubmit(props.submitHandler)}
variant="contained"
className="btn1"
>
{props.editItem ? "Update" : "Add"}
</Button>
)}
<Button
variant="contained"
className="btn1"
onClick={() => {
props.setShowAddUser(false);
props.setItem("");
}}
>
Cancel
</Button>
</div>
</form>
);
}
export default UserForm;
import {useState } from "react";
// useState
const [file, setFile] = useState("");
// input
<input
type="file"
id="file"
onChange={(e) => setFile(e.target.files[0])}
/>
// preview
<img src={file ? URL.createObjectURL(file) : "https://default-image.jpg"} alt="" />
So I've linked my app to a Firebase project and I've created a login form. I'm trying to get the data from the Email and Password inputs and verify it with whats in the Firebase project but for some reason the data isn't being received by Firebase, I was able to achieve it perfectly earlier but now I don't know whats going on...
App.js
import style from "./auth.module.css";
import { useEffect, useRef, useState } from "react";
import { useAuthState } from 'react-firebase-hooks/auth';
import { auth, signInWithEmailAndPassword, signInWithGoogle, registerWithEmailAndPassword } from "../../firebase";
import { CSSTransition } from "react-transition-group";
const Auth = () => {
const [activeMenu, setActiveMenu] = useState("main");
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [user, loading, error] = useAuthState(auth);
const Emailform = () => {
return (
<div className={style.formBox}>
<label className={style.label}>Email:</label>
<form className={style.input}>
<input
type="email"
name="email"
required="true"
/>
</form>
</div>
);
}
const Passform = () => {
return (
<div className={style.formBox}>
<label className={style.label}>Password:</label>
<form className={style.input}>
<input
type="password"
name="password"
required="true" />
</form>
</div>
);
}
let domNode = useClickOutside(() => {
setActiveMenu(false);
});
return (
<div className={style.container}>
<Login />
<Signup />
</div>
);
function AuthType(props) {
return (
<a
href={props.link}
className={style.menuItem}
onClick={() => props.goToMenu && setActiveMenu(props.goToMenu)}
>
{props.children}
</a>
);
}
/* Login */
function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
return (
<CSSTransition in={activeMenu === "main"} unmountOnExit timeout={500}>
<div ref={domNode}>
<div className={style.login}>
<h1 className={style.title}>Clip It</h1>
{/* Email and Password */}
<Emailform value={email} onChange={(e) => setEmail(e.target.value)}/>
<Passform value={password} onChange={(e) => setPassword(e.target.value)}/>
<div className={style.button}>
<input
type="submit"
value="Login"
onClick={() => signInWithEmailAndPassword(email, password)} />
<input
type="submit"
value="Login with Google"
onClick={signInWithGoogle} />
</div>
<div className={style.text}>
<p className={style.plink}>Forgot Password</p>
<div>
Need an account?
<AuthType goToMenu="Signup">click here</AuthType>
</div>
</div>
</div>
</div>
</CSSTransition>
);
}
/* SignUp/Register */
function Signup() {
return (
<CSSTransition in={activeMenu === "Signup"} unmountOnExit timeout={500}>
<div ref={domNode}>
<div className={style.signUp}>
<div className={style.title}> Clip It</div>
<Form label="First Name" type="text" />
<Form label="Last Name" type="Text" />
<Emailform value={email} onChange={(e) => setEmail(e.target.value)}/>
<Form label="Date of Birth" type="date" />
<Passform value={password} onChange={(e) => setPassword(e.target.value)}/>
<Form label="Confirm Password" type="password" />
<div className={style.button}>
<input
type="submit"
value="Sign Up"
onClick={registerWithEmailAndPassword} />
</div>
<div className={style.text}>
have an
<AuthType goToMenu="main"> account</AuthType>
</div>
</div>
</div>
</CSSTransition>
);
}
}
let useClickOutside = (handler) => {
let domNode = useRef();
useEffect(() => {
let clickListener = (event) => {
if (domNode.current && !domNode.current.contains(event.target)) {
handler();
}
};
document.addEventListener("mousedown", clickListener);
return () => {
document.removeEventListener("mousedown", clickListener);
};
});
return domNode;
};
function Form(props) {
return (
<div className={style.formBox}>
<label className={style.label}>{props.label}:</label>
<form className={style.input}>
<input
type={props.input}
name={props.input}
required="true" />
</form>
</div>
);
}
export default Auth;
Firebase.js
import firebase from 'firebase/app';
//import * as firebase from "firebase/app";
import "firebase/auth"
import "firebase/firestore"
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyCq8BAlTWJXG7rFU95QkUTU8U0kXruPA9o",
authDomain: "clip-it-70ff5.firebaseapp.com",
databaseURL: "https://clip-it-70ff5-default-rtdb.firebaseio.com",
projectId: "clip-it-70ff5",
storageBucket: "clip-it-70ff5.appspot.com",
messagingSenderId: "637963668511",
appId: "1:637963668511:web:9cbd1deae03b819153d92a",
measurementId: "G-8S1G78ZH49"
};
const app = !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app();
const auth = app.auth();
const db = app.firestore();
/* Using Google Authentication */
const googleProvider = new firebase.auth.GoogleAuthProvider();
//
const signInWithGoogle = async () => {
try {
await auth.signInWithPopup(googleProvider).then((res) => {
const user = res.user;
const userName = user.displayName;
alert("You're logged in " + userName);
});
}
catch (err) {
console.error(err);
alert(err.message);
}
};
/* Using Email and Password */
// Sign/Logging In
const signInWithEmailAndPassword = async (email, password) => {
try {
await auth.signInWithEmailAndPassword(email.trim(), password);
alert("You've logged in successfuly");
} catch (err) {
console.error(err);
alert("The email or password is incorrect, please try again");
}
};
//SigningUp
const registerWithEmailAndPassword = async (email, password) => {
try {
const res = await auth.createUserWithEmailAndPassword(email, password);
const user = res.user;
await db.collection("users").add({
uid: user.uid,
authProvider: "local",
email,
});
alert("New user added!");
} catch (err) {
console.error(err);
alert(err.message);
}
};
//Sending Password reset link
const sendPasswordResetEmail = async (email) => {
try {
await auth.sendPasswordResetEmail(email);
alert("Password reset link sent!");
} catch (err) {
console.error(err);
alert(err.message);
}
};
const logout = () => {
auth.signOut();
}; // Log out
export {
signInWithGoogle,
signInWithEmailAndPassword,
registerWithEmailAndPassword,
sendPasswordResetEmail,
logout,
auth,
db,
};
You're still assigning props to your Emailform/Passform components in your Login component which you never actually access. So you're never actually setting the state of email or password.
Remove all of the props and rewrite Emailform/Passform like this:
const Emailform = () => {
return (
<div className={style.formBox}>
<label className={style.label}>Email:</label>
<form className={style.input}>
<input
type="email"
name="email"
required="true"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</form>
</div>
);
}
const Passform = () => {
return (
<div className={style.formBox}>
<label className={style.label}>Password:</label>
<form className={style.input}>
<input
type="password"
name="password"
required="true"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</form>
</div>
);
}
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>
);
}
i want to integrate backend codes i.e. rest api to front end reactjs code. i have tried usingaxios . pls help i am new to react.
the code is below:
import React, { useState } from "react";
import "./Register.css";
import { useHistory } from "react-router-dom";
import axios from "axios";
function Register() {
const history = useHistory();
const [data, setData] = useState({
name: "",
phone: "",
password: "",
confirmpassword: "",
});
const [nameErr, setNameErr] = useState({});
const [phoneErr, setPhoneErr] = useState({});
const [passwordErr, setPasswordErr] = useState({});
const [confirmPasswordErr, setConfirmPasswordErr] = useState({});
const InputEvent = (event) => {
const { name, value } = event.target;
setData((preVal) => {
return {
...preVal,
[name]: value,
};
});
};
const formSubmit = (e) => {
e.preventDefault();
const isValid = formValidation();
if (isValid) {
//if form is valid, route
history.push("/myvehicles");
}
};
const formValidation = () => {
const nameErr = {};
const phoneErr = {};
const passwordErr = {};
const confirmPasswordErr = {};
let isValid = true;
if (data.name.trim().length < 4) {
nameErr.nameShort = "name is short";
isValid = false;
}
if (data.phone.trim().length < 10) {
phoneErr.phoneerror = "phone number must have 10 digits";
}
if (data.password.trim().length < 4) {
passwordErr.passwordShort = "password must be 8 characters";
isValid = false;
}
if (!(data.confirmpassword === data.password)) {
confirmPasswordErr.confirmPasswordError = "password must be same";
isValid = false;
}
setNameErr(nameErr);
setPhoneErr(phoneErr);
setPasswordErr(passwordErr);
setConfirmPasswordErr(confirmPasswordErr);
return isValid;
};
axios.post(`https://localhost:5000/`, { InputEvent }).then((res) => {
console.log(res);
console.log(res.data);
});
return (
<div className="signup__container">
<div className="signup__containerInfo">
<h1 className="h1__swari">सवारी नविकरणको लागि</h1>
<hr />
</div>
<form className="register__form" onSubmit={formSubmit}>
<h5 className="h5__form"> Name</h5>
<input
type="text"
placeholder="पुरा नाम लेख्नुहोस्"
name="name"
value={data.name}
onChange={InputEvent}
/>
{Object.keys(nameErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{nameErr[key]}
</div>
);
})}
<h5 className="h5__form"> phone </h5>
<input
type="text"
placeholder="फोन लेख्नुहोस्"
name="phone"
value={data.phone}
onChange={InputEvent}
/>
{Object.keys(phoneErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{phoneErr[key]}
</div>
);
})}
<h5 className="h5__form"> Password </h5>
<input
type="Password"
placeholder="पासवर्ड लेख्नुहोस्s"
name="password"
value={data.password}
onChange={InputEvent}
/>
{Object.keys(passwordErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{passwordErr[key]}
</div>
);
})}
<h5 className="h5__form"> Confirm Password </h5>
<input
type="Password"
placeholder="पुन: पासवर्ड लेख्नुहोस्"
name="confirmpassword"
value={data.confirmpassword}
onChange={InputEvent}
/>
{Object.keys(confirmPasswordErr).map((key) => {
return (
<div className="error__msg" style={{ color: "red" }}>
{confirmPasswordErr[key]}
</div>
);
})}
<p>
<button type="submit" className="signup__registerButton">
Register Now
</button>
</p>
</form>
</div>
);
}
export default Register;
the code is as above . i want the register auth which is token based and wanted to call from the backend and the also send form values to the backend how can i do it?