Prop не меняется с true на false в приложении react, redux, node - PullRequest
1 голос
/ 08 мая 2020

Как сказано в заголовке, у меня есть проверка RegistrationForm для проверки наличия электронной почты пользователя в базе данных. Реквизит userExists. Теперь, если это правда, это означает, что Электронный адрес пользователя существует , поэтому пользователю должно быть показано сообщение, в котором говорится: «Пользователь уже существует». Теперь, если это ложь, он должен быть успешно зарегистрирован и перенаправлен для входа в систему.

Но прямо сейчас я даже не могу зарегистрироваться по электронной почте. На вкладке сети он возвращает 200 и дает ответ: {"message":"User with this email does not exist"}

Может кто-нибудь показать мне, как это сделать? Я имею в виду проверку и сообщение от бэкэнда через redux и обратно в компонент.

Мой код - jibberi sh.

RegistrationForm Компонент

import React, { Component } from "react";
import { registerUser, checkValidUser } from "../../actions/userActions";
import { connect } from "react-redux";
import validator from "validator";
import { Link } from "react-router-dom";
import { toastError } from "../../../utils/toastify";

class RegistrationForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      email: "",
      password: "",
    };
  }

  handleChange = (event) => {
    const { name, value } = event.target;
    this.setState({
      [name]: value,
    });
  };

  handleSubmit = async (event) => {
    event.preventDefault();
    const { username, email, password } = this.state;

    const registrationData = {
      username: this.state.username,
      email: this.state.email,
      password: this.state.password,
    };

    if (!username || !email || !password) {
      return toastError("Credentials should not be empty");
    }

    if (username.length < 6) {
      return toastError("Username should be greater than 6 characters.");
    }

    if (!validator.isEmail(email)) {
      return toastError("Invalid email.");
    }

    if (password.length < 6) {
      return toastError("Password must contain 6 characters.");
    }

    await this.props.dispatch(checkUserExists(email));

    const userExists = this.props.userExists;

    if (!userExists) {
      this.props.dispatch(
        registerUser(registrationData, () => {
          this.props.history.push("/login");
        })
      );
    } else {
      toastError("User with this email already exisits"); // I'm not sure how to show the message if the user email already exists. I want to show the message from backend, but currently I'm just doing it manually
    }
  };

  render() {
    const isRegistrationInProgress = this.props.isRegistrationInProgress;
    return (
      <div>
        <div className="field">
          <p className="control has-icons-left has-icons-right">
            <input
              onChange={this.handleChange}
              name="username"
              value={this.state.username}
              className="input"
              type="text"
              placeholder="Username"
            />
            <span className="icon is-small is-left">
              <i className="fas fa-user"></i>
            </span>
          </p>
        </div>
        <div className="field">
          <p className="control has-icons-left has-icons-right">
            <input
              onChange={this.handleChange}
              name="email"
              value={this.state.email}
              className="input"
              type="email"
              placeholder="Email"
            />
            <span className="icon is-small is-left">
              <i className="fas fa-envelope"></i>
            </span>
          </p>
        </div>
        <div className="field">
          <p className="control has-icons-left">
            <input
              onChange={this.handleChange}
              name="password"
              value={this.state.password}
              className="input"
              type="password"
              placeholder="Password"
            />
            <span className="icon is-small is-left">
              <i className="fas fa-lock"></i>
            </span>
          </p>
        </div>
        <div className="field">
          <div className="control">
            {isRegistrationInProgress ? (
              <button className="button is-success is-loading">Sign Up</button>
            ) : (
              <button onClick={this.handleSubmit} className="button is-success">
                Sign up    console.log("registrationData", registrationData)

              </button>
            )}
            <Link to="/login">
              <p className="has-text-danger">
                Already have an account? Sign In
              </p>
            </Link>
          </div>
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    isRegistrationInProgress: state.registration.isRegistrationInProgress,
    userExists: state.registration.userExists,
  };
};

export default connect(mapStateToProps)(RegistrationForm);

checkUserExists действие

export const checkUserExists = (email) => {
    return async (dispatch) => {
      try {
        const res = await axios.get(`${baseUrl}/users/checkUserExists/${email}`)
        console.log("res=>", res)
        if (res.data.message = "User with this email already exists") {
          dispatch({
            type: "CHECK_USER_EXISTS_SUCCESS",  
          })
        }
      } catch (err) { 
        console.log("error=>", err)
      }
    }
  }

checkUserExists функция контроллера

checkUserExists: async (req, res, next) => {
  const { email } = req.params
  try {
    const user = await User.findOne({ email })
    if (user) {
      return res.status(200).json({ message: "User with this email already exists" })
    } else {
      return res.json({ message: "User with this email does not exist" })
    }
  } catch (error) {
    return next(error)
  }
}

registerUser действие

export const registerUser = (registrationData, redirect) => {
   return async (dispatch) => {
     dispatch({ type: "REGISTRATION_STARTS" })
     try {
       const res = await axios.post(
         `${baseUrl}/users/register`,
         registrationData
       )
       dispatch({
         type: "REGISTRATION_SUCCESS",
         data: { user: res.data.user },
       })
       toastSuccess("Successfully registered")
       redirect()
     } catch (err) {
       dispatch({
         type: "REGISTRATION_ERROR",
         data: { error: err },
       })
     }
   }
 }

registration редуктор

const initialState = () => ({
  isRegistrationInProgress: false,
  isRegistered: false,
  registrationError: null,
  user: {},
  userExists: false,
  error: null,
});

const registration = (state = initialState, action) => {
  switch (action.type) {
    case "REGISTRATION_STARTS":
      return {
        ...state,
        isRegistrationInProgress: true,
        registrationError: null,
      };

    case "REGISTRATION_SUCCESS":
      return {
        ...state,
        isRegistrationInProgress: false,
        registrationError: null,
        isRegistered: true,
        user: action.data,
      };

    case "REGISTRATION_ERROR":
      return {
        ...state,
        isRegistrationInProgress: false,
        registrationError: action.data.error,
        isRegistered: false,
        user: {},
      };
    case "CHECK_USER_EXISTS_SUCCESS":
      return {
        ...state,
        userExists: true,
        error: null
      };
    default:
      return state;
  }
};

export default registration;
...