Home > Enterprise >  axios get data at the first time but not at the second in react
axios get data at the first time but not at the second in react

Time:11-02

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

CodePudding user response:

Please refer this answer for No acess allowed CrossOrigin error here

As for your first appraoch you are using dependency in your useEffect hook readyToSubmit I dont see that anywhere being updated. Your useEffect hook will only run once at the startup and later on whenever the state changes in your case which is readyToSubmit. Since your state is not changing your useEffect hook is not running again. See this React useEffect Doc

For your second approach, your var name is not being updated properly, Propbably that is the reason it does not work second time.

Also there is no need to use useEffect hook for this purpose if you are calling submit handler.

Suggestion I would suggest you to use form libraries such as React Hook Form or Formik to handle form operations. That way you dont have to use useRef hooks unnecessarily.

Secondly, also you can use libraries like MUI or Chakra-UI for form elements and styling

  • Related