Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

javascript - Can't post using useEffect and axios

I'm trying to POST new users using useEffect(). I was able to do using componentDidMount. My hooks are working okay (outside the useEffect), but when It comes to the api.post. The code doesn't post anything. I tried to throw the hook inside the useEffect() but says("Invalid Hook call"). I used some hooks to handle the inputs and when I press a button change the state of my hook normally, but the api doesn't post to my DB. The code enters in the useEffect() but doesn't execute the api.post. Anyone can help me on this? I'm hunting this bug for 2 days. Here is my code:

    //Hooks
    const [name, setUserName] = useState('');
    const [userEmail, setEmail] = useState('');
    const [userPassword, setPassword] = useState('');
    const [avatar, setAvatar] = useState('');

    const [enteredUserName, setEnteredUserName] = useState('');
    const [enteredEmail, setEnteredEmail] = useState('');
    const [enteredPassword, setEnteredPassword] = useState('')

    useEffect((userName, email, password) => {
        api.post('users/signup', {userName: name , email: userEmail, password: userPassword}).then(data => {
            navigation.navigate('Home');
        }).catch(err => {
            if (err === true) {
                Alert.alert('Invalid Credentials')
            }
        }, []);
    })
    const userNameInputHandler = (enteredText) => {
        setEnteredUserName(enteredText)
    };
    
    const userEmailInputHandler = (enteredText) => {
        setEnteredEmail(enteredText);
    };

    const userPasswordHandler = (enteredText) => {
        setEnteredPassword(enteredText);
    };

    const handler = () => {
        setUserName(currentUserNames => [...currentUserNames, enteredUserName]);
        setEmail(currentEmails => [...currentEmails, enteredEmail]);
        setPassword(currentPasswords => [...currentPasswords, enteredPassword]); 
    };

The handler is my Register button. When pressed call the handler().

question from:https://stackoverflow.com/questions/65884092/cant-post-using-useeffect-and-axios

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
useEffect is calling once because you passes [] at the end. i.e

useEffect(()=>{},[]);

if you want to execute useEffect on change of something then pass that as dependency i.e []

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...