I’m trying to pass data from the child component to the parent component by calling a function. In the parent element I create a function that receives a value as a parameter and calls setLogin passing this received value. I call this function in the child component passing the data I want to send as a parameter. When I print the login variable in the parent component, it prints an object with the empty email.
I’ve done this before and it worked, but now it’s not working.
What am I forgetting?
Login.js:
import "../styles/Login.css";
import { Link } from "react-router-dom";
import { useState } from "react";
import Axios from "axios";
function Login({ childToParentLogin }){
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [response, setResponse] = useState("");
async function handleSubmit(){
if(email.length === 0){
alert("Enter your e-mail.");
}else if(password.length === 0){
alert("Enter your password.");
}else{
const url = "http://localhost/metric/src/api/login.php";
let formData = new FormData();
formData.append("email", email);
formData.append("password", password);
try {
const data = await Axios.post(url, formData);
if(data.data === "Correct data"){
childToParentLogin(email);
window.location.href="http://localhost:3000/login/usuario";
}
setResponse(data.data);
}catch(erro){
console.log(erro);
}
}
}
return (
...
);
}
export default Login;
RouteSwitch.js:
import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Nav from "./Nav";
import App from "../App";
import Login from "./Login";
import Register from "./Register";
import User from "./User";
import Test from "./Test";
import { useState } from "react";
function RouteSwitch(){
const [login, setLogin] = useState({email: ""});
function childToParentLogin(childData){
setLogin({email: childData});
console.log(login);
}
return (
<BrowserRouter>
<Nav></Nav>
<Routes>
<Route path="/" exact element={<App />} />
<Route path="/login" exact element={<Login childToParentLogin={ childToParentLogin } />} />
<Route path="/login/user" exact element={<User login={ login } />} />
<Route path="/register" exact element={<Register />} />
<Route path="/test" exact element={<Test />} />
</Routes>
</BrowserRouter>
);
}
export default RouteSwitch;
>Solution :
You are referencing the value of login before the state has had a chance to update. If you were to change the value in the console log as shown below, it would print the new email address.
function childToParentLogin(childData){
setLogin({email: childData});
console.log(childData);
}
If you are wanting to do something with the login data after if has changed, you should use a useEffect hook with login as a value in the dependency array.