Reputation: 622
I want to post the data from axios but I am getting invalid hook call error. What I am doing wrong here. Here's my code
const Login = (props) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const onLoginSubmit = (event) => {
event.preventDefault();
const url = baseUrl + '/';
const loginData = {
email: email,
password: password,
};
setIsLoading(true);
useEffect(async () => {
await axios
.post(`${url}users/login`, loginData)
.then((res) => {
console.log(res.data);
AsyncStorage.setItem('token', JSON.stringify(res.data.token));
props.navigation.navigate('MainHome');
})
.catch((error) => {
setError(error.res.data);
setLoading(false);
setIsLoading(false);
});
});
};
Upvotes: 0
Views: 135
Reputation: 53984
You must call hooks on top-level, see Rules Of Hooks.
Don’t call Hooks inside loops, conditions, or nested functions.
const Login = (props) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const fetch = async () => {
const url = baseUrl + "/";
const loginData = {
email: email,
password: password,
};
await axios
.post(`${url}users/login`, loginData)
.then((res) => {
console.log(res.data);
AsyncStorage.setItem("token", JSON.stringify(res.data.token));
props.navigation.navigate("MainHome");
})
.catch((error) => {
setError(error.res.data);
setLoading(false);
setIsLoading(false);
});
};
if (loading) {
fetch();
}
}, [loading, email, password]);
const onLoginSubmit = (event) => {
event.preventDefault();
setIsLoading(true);
};
};
Upvotes: 3