результат приращения значения ax ios в хуках рендерится со старым значением, а затем снова рендерит с новым значением. Я хочу работать только с обновленным значением - PullRequest
0 голосов
/ 04 апреля 2020

Проблема

Я сталкиваюсь с проблемой в использовании, если предыдущая отправка верна, то отправка формы с данными, уже существующими в mongodb, сначала вызывает предупреждение об успехе, а затем предупреждение о дублированных данных (в useselecter vaeriable) actionDataState. success "возвращает значение true, если отправка данных успешно, false, если e)

enter code here

import React from "react";

// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";

// @material-ui/icons
import PermIdentity from "@material-ui/icons/PermIdentity";

// core components
import GridContainer from "components/Grid/GridContainer.js";
import GridItem from "components/Grid/GridItem.js";
import Button from "components/CustomButtons/Button.js";
import CustomInput from "components/CustomInput/CustomInput.js";
import Card from "components/Card/Card.js";
import CardBody from "components/Card/CardBody.js";
import CardHeader from "components/Card/CardHeader.js";
import CardIcon from "components/Card/CardIcon.js";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import SweetAlert from "react-bootstrap-sweetalert";

import stylesAlert from "assets/jss/material-dashboard-pro-react/views/sweetAlertStyle.js";
import stylesCard from "assets/jss/material-dashboard-pro-react/views/userProfileStyles.js";
import stylesCustom from "assets/jss/material-dashboard-pro-react/customSelectStyle.js";


/*Redux code start*/
import { useDispatch ,useSelector } from "react-redux";
import {useEffect} from 'react';
import { addTeacher , clearAddTeacher } from './../../../actions';
import PASSWORD from './teacherdefaultpassword';
/*Redux code end*/

const useStyles = makeStyles(stylesCustom,stylesCard,stylesAlert);
const useStylesA = makeStyles(stylesAlert);
export default function Aaddteacher() {
  const classes = useStyles();
  const classesA = useStylesA();
  /*Redux code start*/
  const dispatch = useDispatch();
  const actionDataState = useSelector(state => state.user.data, []) || [];

  /*Redux code end*/
  const [teacherName, setteacherName] = React.useState("");
  const [teacherNameState, setteacherNameState] = React.useState("");
  const [Email, setEmail] = React.useState("");
  const [registerEmailState, setregisterEmailState] = React.useState("");
  const [department, setdepartment] = React.useState("");
  const [departmentState, setdepartmentState] = React.useState("");
  const [employeeCode, setemployeeCode] = React.useState("");
  const [employeeCodeState, setemployeeCodeState] = React.useState("");
  const [simpleSelect, setSimpleSelect] = React.useState("");
  const [count,setcount] = React.useState(0);
  const [alert, setAlert] = React.useState(null);

  useEffect(() => {
    console.log(actionDataState.success)
    if(actionDataState.success===false )
    {
      console.log(actionDataState.success)
      cancelDetele("Duplicate DATA or server is not responding")
    }
  },[actionDataState.success,cancelDetele]);

  useEffect(() => {
    console.log()
    console.log(actionDataState.success)
    if(actionDataState.success === true  ){
      console.log(actionDataState.success)
      resetvalues()
      successAlert()
    }
  },[actionDataState.success,count,successAlert]);



  // const onclickcheckingdata=(status)=>{
  //   if(status===false){
  //     cancelDetele("Duplicate DATA or server is not responding")
  //   }
  // }
  const hideAlert = () => {
    setAlert(null);
  };
  // function that returns true if value is email, false otherwise
  const verifyEmail = value => {
    var emailRex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (emailRex.test(value)) {
      return true;
    }
    return false;
  };
  const handleSimple = event => {
    setSimpleSelect(event.target.value);
  };
  const verifyLength = (value, length) => {
    if (value.length >= length) {
      return true;
    }
    return false;
  };

  const cancelDetele = (text) => {
    setAlert(
      <SweetAlert
        danger
        style={{ display: "block", marginTop: "-100px" }}
        title="Cancelled"
        onConfirm={() => hideAlert()}
        onCancel={() => hideAlert()}
        confirmBtnCssClass={classesA.button + " " + classesA.success}
      >
        {text}
      </SweetAlert>
    );
  };
  const successAlert = () => {
    setAlert(
      <SweetAlert
        success
        style={{ display: "block", marginTop: "-100px" }}
        title="Form Submitted !!!"
        onConfirm={() => hideAlert()}
        onCancel={() => hideAlert()}
        confirmBtnCssClass={classesA.button + " " + classesA.success}
      >
      </SweetAlert>
    );
  };
  const submitForm = (e) => {
    e.preventDefault();
    if (teacherNameState !== "success" ) {
      setteacherNameState("error");
      cancelDetele("The Name field is incorrect or empity")
      return null;
    }
    if (registerEmailState !== "success") {
      setregisterEmailState("error");
      cancelDetele("The Email field is incorrect or empity")
      return null;
    }
    if (departmentState !== "success") {
      setdepartmentState("error");
      cancelDetele("The Department field is incorrect or empity")
      return null;
    }
    if (employeeCodeState !== "success") {
      setemployeeCodeState("error");
      cancelDetele("The Employee Code field is incorrect or empity")
      return null;
    }
    if (simpleSelect === "") {
      cancelDetele("The Designation field is empity")
      return null;
    }
    //first make request then alert true
    dispatch( addTeacher({
      fullname: teacherName,
      email: Email,
      department: department,
      employeecode: employeeCode,
      designation: simpleSelect,
      password: PASSWORD
    }))
    if(actionDataState.success === true){
      setcount(count +1 )
    }
  }
  const  resetvalues=()=>{  
    setteacherName("")
    setteacherNameState("")
    setEmail("")
    setregisterEmailState("")
    setdepartment("")
    setdepartmentState("")
    setemployeeCode("")
    setemployeeCodeState("")
    setSimpleSelect("")
  } 
// CLEAR THE SCREEN

  return (
    <div>
      {console.log("render")}
      <GridContainer>
        <GridItem xs={12} sm={12} md={12}>
          <Card>
            <CardHeader color="primary" icon>
              <CardIcon color="primary">
                <PermIdentity />
              </CardIcon>
              <h4 className={classes.cardIconTitle}>
                Add Teacher
              </h4>
            </CardHeader>

            {alert}
            <CardBody>
              <form onSubmit={submitForm} >
                <GridContainer>
                  <GridItem xs={12} sm={6} md={6} lg={6}>
                    <CustomInput
                      success={teacherNameState === "success"}
                      error={teacherNameState === "error"}
                      value={teacherName}
                      labelText="Teacher Name"
                      id="teacher-name"
                      formControlProps={{
                      fullWidth: true
                      }}
                      inputProps={{
                      onChange: event => {
                          if (verifyLength(event.target.value, 1)) {
                          setteacherNameState("success");
                          } else {
                          setteacherNameState("error");
                          }
                          setteacherName(event.target.value);
                      },
                      type: "text",
                      autoComplete: "off"
                      }}
                    />
                  </GridItem>
                  <GridItem xs={12} sm={12} md={6}>
                    <CustomInput
                      success={registerEmailState === "success"}
                      error={registerEmailState === "error"}
                      value={Email}
                      labelText="Email Address "
                      id="register-email"
                      formControlProps={{
                        fullWidth: true
                      }}
                      inputProps={{
                        onChange: event => {
                          if (verifyEmail(event.target.value)) {
                            setregisterEmailState("success");
                          } else {
                            setregisterEmailState("error");
                          }
                          setEmail(event.target.value);
                        },
                        type: "email"
                      }}
                    />
                  </GridItem>
                </GridContainer>
                <GridContainer>
                <GridItem xs={12} sm={4} md={4} lg={4}>
                  <CustomInput
                      success={departmentState === "success"}
                      error={departmentState === "error"}
                      value={department}
                      labelText="Department"
                      id="department"
                      formControlProps={{
                        fullWidth: true
                      }}                    
                      inputProps={{
                        onChange: event => {
                          if (verifyLength(event.target.value, 1)) {
                            setdepartmentState("success");
                          } else {
                            setdepartmentState("error");
                          }
                          setdepartment(event.target.value);
                        },
                        type: "text",
                        autoComplete: "off"
                      }}
                    />
                  </GridItem>
                <GridItem xs={12} sm={4} md={4} lg={4}>
                  <CustomInput
                      success={employeeCodeState === "success"}
                      error={employeeCodeState === "error"}
                      value={employeeCode}
                      labelText="Employee Code"
                      id="employee-code"
                      formControlProps={{
                        fullWidth: true
                      }}                    
                      inputProps={{
                        onChange: event => {
                          if (verifyLength(event.target.value, 1)) {
                            setemployeeCodeState("success");
                          } else {
                            setemployeeCodeState("error");
                          }
                          setemployeeCode(event.target.value);
                        },
                        type: "text",
                        autoComplete: "off"
                      }}
                    />
                  </GridItem>
                  <GridItem xs={12} sm={4} md={4} lg={4}>
                    <FormControl
                      fullWidth
                      className={classes.selectFormControl}
                    >
                      <InputLabel
                        htmlFor="select-designation"
                        className={classes.selectLabel}
                      >
                        Select Designation
                      </InputLabel>
                      <Select
                        MenuProps={{
                          className: classes.selectMenu
                        }}
                        classes={{
                          select: classes.select
                        }}
                        value={simpleSelect}
                        onChange={handleSimple}
                        inputProps={{
                          name: "select-designation",
                          id: "select-designation"
                        }}
                      >
                        <MenuItem
                          disabled
                          classes={{
                            root: classes.selectMenuItem
                          }}
                        >
                          Select Designation
                        </MenuItem>
                        <MenuItem
                          classes={{
                            root: classes.selectMenuItem,
                            selected: classes.selectMenuItemSelected
                          }}
                          value="Jonir Lecturer"
                        >
                          Jonir Lecturer
                        </MenuItem>
                        <MenuItem
                          classes={{
                            root: classes.selectMenuItem,
                            selected: classes.selectMenuItemSelected
                          }}
                          value="Lecturer"
                        >
                          Lecturer
                        </MenuItem>
                        <MenuItem
                          classes={{
                            root: classes.selectMenuItem,
                            selected: classes.selectMenuItemSelected
                          }}
                          value="Assistent Lecturer"
                        >
                          Assistent Lecturer
                        </MenuItem>
                      </Select>
                    </FormControl>
                  </GridItem>
                </GridContainer>
                <GridContainer justify="center">
                <GridItem xs={12} sm={12} md={6}>
                    <CardBody style={{ textAlign: "center" }}>
                      <Button 
                        type="submit"
                        color="primary" 
                        className={classes.updateProfileButton}
                      >
                        Add Teacher
                      </Button>
                    </CardBody>
                </GridItem>
              </GridContainer>
              </form>
            </CardBody>
          </Card>
        </GridItem>
      </GridContainer>
    </div>
  );
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...