I am going to write an login page,fetch and match the data from the input and the database.But it works after i save the react change in vs code and the axios.get can fetch data.But when i try to logout and login again, it wont work and the axios cannot get any data.I have use two approach one is with useEffect the other without.But both work at the first and cant work in the second times.The first one even show the XML error with no access allow crossorgin. My code:
const Login=(props)=> {
const [password,setPassword]=useState("null");
const [readytosubmit,setReadytosubmit]=useState(false)
//const [ablelogin,setAblelogin]=useState(false)
const nameRef=useRef("");
const navigate=useNavigate();
var name=nameRef.current.value;
const passwordRef=useRef("hfs");
console.log(name)
/* first approach(with useCreate)
useEffect(()=>{
const getArticles = async () => {
const res = await Axios.get("http://localhost:8080/api/password/"+name);
setPassword(res.data);
//console.log(password);
console.log(res.data)};getArticles()} ,[password] )
// getArticles()}} ,[readytosubmit]
console.log(password)
function handlesubmit(e){
//must need
e.preventDefault();
//setAblelogin(true)
if(passwordRef.current.value.toString()===password.toString()){
console.log("Ture Password")
props.login();
navigate("/")
}else{
console.log("false password")
}
}; */
function handlesubmit(e){
e.preventDefault();
getArticles();
}
//second approach(without useEffect)
const getArticles = async () => {
const res = await Axios.get("http://localhost:8080/api/password/"+name);
console.log(res.data)
if(passwordRef.current.value.toString()===res.data.toString()){
console.log("Ture Password")
props.login();
navigate('/');
}else{
console.log("false password")
}
};
return (
<><div className='Registerform'>
<h3>Login Form</h3><br></br>
<Form onSubmit=/* {handlesubmit} */{handlesubmit} >
<Form.Group className="mb-3" controlId="formBasicName">
<Form.Label>Username</Form.Label>
<Form.Control ref={nameRef} type="username" placeholder="Enter your username" />
</Form.Group><br></br>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control ref={passwordRef} type="password" placeholder="Password" />
</Form.Group><br></br>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</div>
<Button onClick={props.login} variant="primary">Primary</Button> </>) }//<--- this works fine <Link
//to={{pathname:'/layout',state:loginStatus}} />*/)}
export default Login ;
my console.log(first time): alex
login.jsx:25 alex
login.jsx:25 alex
login.jsx:25 alex
login.jsx:63 123456
login.jsx:65 Ture Password
index.js:32 loginstatusfalse
index.js:33 login
layout.jsx:28 layout: true
layout.jsx:28 layout: true
my console.log(second time):
layout: false
layout.jsx:28 layout: false
login.jsx:25 undefined
login.jsx:25 undefined
login.jsx:63 <--no result showed
login.jsx:69 false password