Почему я не получаю предупреждение, когда выдается ошибка при отправке? - PullRequest
0 голосов
/ 19 марта 2020

Я довольно новичок, чтобы отреагировать на нативное и пытаюсь составить свое первое приложение rn / expo, однако я столкнулся с проблемой, над которой я застрял.

Я использовал fetch api для вызовов на firebase auth и db, но мне пришлось портировать на firebase sdk (js / web), так как мне нужно было использовать хранилище firebase для изображений. Я преобразовал все, и это работает хорошо, за исключением части обработки ошибок.

Здесь ниже у меня есть AuthScreen. js, где я выполняю функцию, чтобы войти или зарегистрировать пользователя,

const [error, setError] = useState(null);

useEffect(() => {
    console.log('Entered useEffect');
    if (error) {
      Alert.alert('Error Occured', error, [{ text: 'Close' }]);
    }
  }, [error]);

  const authHandler = async () => {
    let action;

    if (isLogin) {
      action = authActions.login(email, password);
    } else {
      action = authActions.signup(email, password, name);
    }
    setError(null);
    setIsLoading(true);
    try {
      await dispatch(action);
    } catch (err) {
      console.log('Error', err);
      setError(err.message);
      setIsLoading(false);
    }
  };

<Button
  size='small'
  style={styles.button}
  status='basic'
  onPress={authHandler}
  icon={isLoading ? () => <ActivityIndicator /> : null}
>
   {isLoading ? null : 'PROCEED'}
</Button>

Это действие в моем магазине приставок,

export const login = (email, pw) => {
  return async dispatch => {
    firebase
      .auth()
      .signInWithEmailAndPassword(email, pw)
      .then(() => {
        const userId = firebase.auth().currentUser.uid;
        firebase
          .database()
          .ref('/users/' + userId)
          .once('value')
          .then(snapshot => {
            const data = snapshot.val();
            console.log('data', data);
            dispatch({ type: REMOVE_USER });
            dispatch({ type: GET_USER, user: data.name });
          })
          .catch(err => console.log('err.message', err.message));
      })
      .catch(err => {
        let message = 'An error has occured!';

        if (err.code === 'auth/invalid-email') {
          message = 'Invalid email address!';
        } else if (err.code === 'auth/user-not-found') {
          message = 'No account with such credentials!';
        } else if (err.code === 'auth/wrong-password') {
          message = 'Incorrect password! Try again.';
        }

        throw new Error(message);
      });
  };
};

Когда я пытаюсь воспроизвести ошибку, я просто получаю всплывающую ошибку, подобную этой,

Error

Это должно было быть предупреждение. Я не могу понять это ..

1 Ответ

0 голосов
/ 21 марта 2020

Нашли решение!

Добавление await решило бы проблему. Любая асин c отправка потребовала бы ожидание .

export const login = (email, pw) => {
return async dispatch => {
    await firebase
      .auth()
      .signInWithEmailAndPassword(email, pw)
      .then(() => {
        const userId = firebase.auth().currentUser.uid;
        firebase
          .database()
          .ref('/users/' + userId)
          .once('value')
          .then(snapshot => {
            const data = snapshot.val();
            dispatch({ type: REMOVE_USER });
            dispatch({ type: GET_USER, user: data.name });
          })
          .catch(err => console.log('err.message', err.message));
      })
      .catch(err => {
        let message = 'An error has occured!';

    if (err.code === 'auth/invalid-email') {
      message = 'Invalid email address!';
    } else if (err.code === 'auth/user-not-found') {
      message = 'No account with such credentials!';
    } else if (err.code === 'auth/wrong-password') {
      message = 'Incorrect password! Try again.';
    }

    throw new Error(message);
  });
  };
};
...