简体   繁体   中英

Getting undefined values from Input Value in ReactJS

I am unable to get the values of email and password from the FormControl Input values. I am using the BaseWeb ReactUI framework for the field UI.

Need help stuck on this issue.

import { FormControl } from 'baseui/form-control';
import { Input } from 'baseui/input';
import { useStyletron } from 'baseui';
import { Alert } from 'baseui/icon';
import { Button } from 'baseui/button';
import { TiUserAddOutline } from "react-icons/ti";
import Axios from "axios";
import { useHistory, Link } from 'react-router-dom';
import { validate as validateEmail } from 'email-validator'; // add this package to your repo with `$ yarn add email-validator`
import { Select } from 'baseui/select';
import { Checkbox } from 'baseui/checkbox';

function SelectAtStart(props) {
  const [css] = useStyletron();
  return (
    <div className={css({ display: 'flex' })}>
      <div className={css({ width: '200px', paddingRight: '8px' })}>
        <Select
          options={props.options}
          labelKey="id"
          valueKey="gender"
          onChange={({ value }) => props.onSelectChange(value)}
          value={props.selectValue}
          id={props.id}
        />
      </div>
      <Input
        onChange={e => props.onInputChange(e.target.value)}
        value={props.inputValue}
      />
    </div>
  );
}

function Negative() {
  const [css, theme] = useStyletron();
  return (
    <div
      className={css({
        display: 'flex',
        alignItems: 'center',
        paddingRight: theme.sizing.scale500,
        color: theme.colors.negative400,
      })}
    >
      <Alert size="18px" />
    </div>
  );
}

export function RegisterFields() {
  const history = useHistory();
  const [css, theme] = useStyletron();
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [checked, setChecked] = React.useState(true);
  const [startInputValue, setStartInputValue] = React.useState('');
  const [startSelectValue, setStartSelectValue] = React.useState(
    [],
  );
  const [isValid, setIsValid] = React.useState(false);
  const [isVisited, setIsVisited] = React.useState(false);
  const shouldShowError = !isValid && isVisited;
  const onChangeEmail = ({ target: { email } }) => {
    setIsValid(validateEmail(email));
    setEmail(email);

  };
  
  const onChangePassword = ({ target: { password } }) => {
    setIsValid(true);
    setPassword(password);
  }

  
  const handleSubmit = (event) => {
    event.preventDefault();

    console.log(email, password)
    Axios.defaults.headers.common = {
      "Content-Type": "application/json"
    }

    Axios.post("http://localhost:5000/api/signup", {
      email: email,
      password: password,
      firstName: startInputValue,
      lastname: startInputValue,
      agreement: checked
    }).then((res) => {
      if (res.status === 200) {
        const path = '/dashboard'
        history.push(path)
        console.log(res)
      }
      else {
        console.log("Unable to create account")
      }
    })
  }

  return (
    <form
      onSubmit={handleSubmit}
      className={css({
        marginTop: theme.sizing.scale1000,
      })}
    >
      <FormControl
        label="Your Email"
        error={
          shouldShowError
            ? 'Please input a valid email address'
            : null
        }
      >
        <Input
          id="email"
          value={email}
          onChange={onChangeEmail}
          onBlur={() => setIsVisited(true)}
          error={shouldShowError}
          overrides={shouldShowError ? { After: Negative } : {}}
          type="email"
          required
        />

      </FormControl>
      <FormControl
        label="Your Password"
        error={
          shouldShowError
            ? 'Your password is incorrect'
            : null
        }
      >
        <Input
          id="password"
          value={password}
          onChange={onChangePassword}
          onBlur={() => setIsVisited(true)}
          error={shouldShowError}
          overrides={shouldShowError ? { After: Negative } : {}}
          type="password"
          required
        />

      </FormControl>
      <FormControl
        label="Your Full Name"
      >
        <SelectAtStart
          inputValue={startInputValue}
          onInputChange={v => setStartInputValue(v)}
          selectValue={startSelectValue}
          onSelectChange={v => setStartSelectValue(v)}
          options={[
            { id: 'Mr', gender: 'Male' },
            { id: 'Mrs', gender: 'Women' },
            { id: 'Ms', gender: 'Female' },
            { id: 'None', gender: 'Dont Say' },
          ]}
          id="start-id"
        />
      </FormControl>
      <FormControl>
        <Checkbox
          checked={checked}
          onChange={() => setChecked(!checked)}
        >
          <div className={css({
            color:'grey'
          })}
          >I hereby agree to the terms and conditons of the platform.</div>
        </Checkbox>
      </FormControl>
      <Button type="submit">
        <TiUserAddOutline style={{ marginRight: '10px' }} />
        Create Account
      </Button>
      <div>
        <p style={{ marginTop: '10px', color: 'grey' }} >To go back to login, please <Link to='/'>click here</Link></p>
      </div>
    </form>
  );
}

I believe it's because you keep setting it to the email/password value of target which is "undefined".

e.target.email = undefined
e.target.password = undefined

Try with this approach:

const onChangeEmail = e =>
{
    setIsValid(validateEmail(e.target.value));
    setEmail(e.target.value);
};

const onChangePassword = e =>
{
    setIsValid(true);
    setEmail(e.target.value);
};

Here you can see that all text inputs are stored in a value of targeted event ( event.target.value )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM