S
S
sinevik2018-05-15 15:49:05
JavaScript
sinevik, 2018-05-15 15:49:05

How can I return the correct result?

import { ADD_USER} from './actionTypes';
import { HELLO} from './actionTypes';
import firebase from 'react-native-firebase';

export const addUser = (surname, name, patronymic, phone) => {
    return dispatch => {
      var db = firebase.firestore();
      let user = {
        surname: surname,
        name: name,
        patronymic: patronymic,
        phone: phone
      }
      var result = 'начальный';
      var docRef = db.collection('users').doc(user.phone);
      docRef.get().then(function(doc) {
      if (doc.exists) {
          result = 'Такой номер уже есть';
          console.log('Такой номер уже есть');
      }else{
          db.collection('users').doc(user.phone).set(user);
          result = true;
          console.log(true);
      }
      }).catch(function(error) {
          result = 'Произошла ошибка';
          console.log('Произошла ошибка');
      });
      return result;
    };
};

When calling this function from the redux store
let result = this.props.onAddUser(
this.state.controls.surname.value,
this.state.controls.name.value,
this.state.controls.patronymic.value,
this.state.controls.phone.value
)
console.log(result);

result is always equal to 'initial'. Although in the console it shows ('This number already exists'). How can I properly overwrite result?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Zharov, 2018-05-15
@sinevik

import {ADD_USER} from './actionTypes';
import {HELLO} from './actionTypes';
import firebase from 'react-native-firebase';

export const addUser = (surname, name, patronymic, phone) => {
    return async dispatch => {
        let db = firebase.firestore();
        let user = {
            surname: surname,
            name: name,
            patronymic: patronymic,
            phone: phone,
        };
        let result = 'начальный';
        let docRef = db.collection('users').doc(user.phone);
        try {
            let doc = await docRef.get()
            if (doc.exists) {
                result = 'Такой номер уже есть';
                console.log('Такой номер уже есть');
            } else {
                db.collection('users').doc(user.phone).set(user);
                result = true;
                console.log(true);
            }
        } catch (e) {
            result = 'Произошла ошибка';
            console.log('Произошла ошибка');
        }
        return result;
    };
};

let result = this.props.onAddUser(
    this.state.controls.surname.value,
    this.state.controls.name.value,
    this.state.controls.patronymic.value,
    this.state.controls.phone.value,
).then(result => console.log(result))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question