Как извлечь sh историю в указанный c компонент, используя asyn c fetch в реаги js - PullRequest
0 голосов
/ 28 января 2020

Я пишу страницу входа, используя reactjs, где я генерирую свой OTP в отдельном flask приложении. Я вызываю функцию по нажатию кнопки, которая выбирает API и проверяет, соответствует ли OTP или нет. Он обеспечивает правильные значения журнала на задней стороне, но на лицевой стороне, даже если OTP недействителен, он перемещает историю на следующую страницу, на которой он должен оставаться на той же странице. Что не так в моем коде и как это исправить? мой код переднего конца выглядит следующим образом:

import React, { Component } from "react";
import "../pod.css";
export default class OTPVerify extends Component {
  constructor(props) {
    super(props);
    //const { params } = this.props.location.state;
    //var data = this.props.location.userPhone;

    console.log(this.props.history.location.state.userPhone);
    this.state = {
      userPhone: this.props.history.location.state.userPhone,
      userotp: "",
      verified: false,
      isMounted: false,
      existingUser: false
    };
    this.handleChange = this.handleChange.bind(this);
  }
  componentDidMount() {
    this.setState(
      {
        isMounted: true
      },
      function() {}
    );
  }

  handleChange(event) {
    //console.log(event.target.value);
    const name = event.target.name;
    const value = event.target.value;

    this.setState({ [name]: value });
  }

  verifyOTP = event => {
    if (this.state.isMounted == true) {
      console.log("XXX");
      if (this.isOTPValid(this.state.userotp)) {
        this.forwardToHomePage();
      } else {
        alert("please enter a valid OTP");
        event.preventDefault();
      }
    }
    //
  };
  async isOTPValid(phone) {
    if (phone.length === 6) {
      var val = this.checkOTP();
      console.log(val);
      return val;
      //console.log(this.state.verified);
    } else {
      return false;
    }
  }

  async checkOTP() {
    await fetch("http://192.168.43.212:5000/api/verifyOTP", {
      method: "POST",
      credentials: "include",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        pod_Otp: this.state.userotp,
        userPhone: this.state.userPhone
      })
    })
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            verified: responseJson.validOTP,
            existingUser: responseJson.clientExists
          },
          function() {
            console.log(this.state.verified);
            console.log(this.state.existingUser);
          }
        );
        return this.state.verified;
      })
      .catch(error => {
        console.log(error);
      });
  }
  forwardToHomePage() {
    if (this.state.existingUser) {
      this.props.history.push("/Home", { userPhone: this.state.userPhone });
    } else {
      this.props.history.push("/customerProfile", {
        userPhone: this.state.userPhone,
        edit_enabled: true
      });
    }
  }
  render() {
    return (
      <div className="login-form">
        <form method="post">
          <h2 className="text-center">Sign in</h2>

          <img
            src="cinqueterre.jpg"
            className="rounded-circle"
            alt="Book Pandit"
          />

          <div className="or-seperator">
            <i>or</i>
          </div>
          <div className="form-group">
            <div className="input-group">
              <span className="input-group-addon">
                <i className="fa fa-user"></i>
              </span>
              <input
                type="text"
                className="form-control"
                name="userotp"
                required="required"
                onChange={this.handleChange}
              ></input>
            </div>
          </div>

          <div className="form-group">
            <button
              type="submit"
              className="btn btn-success btn-block login-btn"
              onClick={this.verifyOTP}
            >
              Verify OTP
            </button>
          </div>
        </form>
      </div>
    );
  }
}

1 Ответ

0 голосов
/ 28 января 2020

isOTPValid - это асинхронная c функция, а также checkOTP. checkOTP правильно ожидает ответа на выборку, а isOTPValid - нет. В verifyOTP вы проверяете текущее возвращаемое значение isOTPValid, которое, поскольку не ожидается, является ожидающим обещанием. Вам нужно дождаться разрешения неявного обещания, которое возвращает checkOTP.

verifyOTP = event => {
  if (this.state.isMounted == true) {
    console.log("XXX");
    if (this.isOTPValid(this.state.userotp)) {
      this.forwardToHomePage();
    } else {
      alert("please enter a valid OTP");
      event.preventDefault();
    }
  }
};

async isOTPValid(phone) {
  if (phone.length === 6) {
    var val = await this.checkOTP(); // this is a promise!!! you should await its resolution
    console.log(val);
    return val;
    //console.log(this.state.verified);
  } else {
    return false;
  }
}
...