简体   繁体   中英

getting invalid hook call in react native useEffect()

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);
        });
    });
  };

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);
  };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM