'Can't combine a hook and a function in onClick event

I'm new to React. This is a 3 step registration form. In the last step - StepThree, I've been trying to have a hook - handleDateChange and a function - HandleUserInfo work on one click and send the registration form to the database. In the previous version this code was split into two steps, in (old)StepThree you had the date of birth and in the last one (old StepFour) you had the photo upload.I've joined them but it doesn't work.In my file (new) StepThree.js I have the following code

const StepThree = () => {
  const history = useHistory();
  const classes = useStyles();
  const [selectedDate, setSelectedDate] = useState(
    new Date('2014-08-18T21:11:54')
  );

  useEffect(() => {
    localStorage.setItem('isInsideSteps', 3);
  }, []);

  const handleDateChange = (date) => {
    setSelectedDate(date);
  };

  // Old Step 4

  const { setUser } = useContext(UserContext);
  const user = JSON.parse(localStorage.getItem('user'));
  const [showErrDlg, setShowErrDlg] = useState(false);
  const [img, setImg] = useState({ urlString: '', file: {} });

  const uploadImage = (event) => {
    setImg({
      urlString: URL.createObjectURL(event.target.files[0]),
      file: event.target.files[0]
    });
  };

  const onDialogClose = () => {
    setShowErrDlg(false);
  };

  const completeSubmit = (imgUrl) => {
    User.createProfile({
      img: imgUrl,
      token: user.token,
      // eslint-disable-next-line
      account: { _id: user.account._id },
      ...user.account
    })
      .then((res) => {
        localStorage.removeItem('isInsideSteps');
        setUserData(res.data.account, setUser);
        history.push('/');
      })
      .catch((err) => {
        setShowErrDlg(true);
      });
  };

  const sendToBucket = (event) => {
    event.preventDefault();
    const formData = new FormData();
    formData.append('image', img.file);
    Files.upload_image(formData).then((res) => {
      completeSubmit(res.image_url);
    });
  };

  const handleUserInfo = () => {
    const updatedUserInfo = {
      dob: selectedDate
    };
    updateUser(updatedUserInfo);

    history.push('/');
  };

When I put the handleUserInfo function in the onClick event in the Submit Button the data from previous steps doesn't send but the date of birth. On the other hand when I put handleDateChange (like in the code below) everything sends but the date of birth. This is the pertinent code in "return".

<>
      <Navbar justImage />
      <Container component="main" maxWidth="sm" alignItems="center">
        <div className={classes.paper}>
          <div className={classes.title}>Register</div>
          <div className={classes.textDescription}>
            Upload a profile picture
          </div>
        </div>
        <form
          noValidate
          onSubmit={(e) => sendToBucket(e, handleUserInfo)}
          className={classes.uploadImage}
        >
          <div className={classes.marginBottom}>
            {img.urlString !== '' ? (
              <img src={img.urlString} className={classes.image} alt="" />
            ) : (
              <div>
                <AccountCircleIcon className={classes.userIcon} />
              </div>
            )}

            <input
              accept="image/*"
              className={classes.input}
              style={{ display: 'none' }}
              id="raised-button-file"
              type="file"
              onChange={(e) => uploadImage(e)}
            />
            <label htmlFor="raised-button-file">
              <SubmitButton type="button" variant="outlined" component="span">
                Choose File
              </SubmitButton>
            </label>
          </div>
          <div className={classes.paper}>
            <div className={classes.paragraphDob}>Enter your date of birth</div>
          </div>
          <MuiPickersUtilsProvider utils={DateFnsUtils}>
            <KeyboardDatePicker
              InputProps={{ disableUnderline: true }}
              className={classes.dataPicker}
              disableToolbar
              disableFuture
              variant="inline"
              format="MM/dd/yyyy"
              margin="normal"
              id="date-picker-inline"
              label="Date of brith"
              value={selectedDate}
              onChange={handleDateChange}
              KeyboardButtonProps={{
                'aria-label': 'change date'
              }}
            />
          </MuiPickersUtilsProvider>

          <Grid container className={classes.marginTop}>
            <Grid item xs>
              <SubmitButton
                type="submit"
                value="Continue"
                onClick={handleDateChange}
                variant="contained"
                disabled={img.urlString === ''}
              >
                Complete
              </SubmitButton>
            </Grid>
            <Grid item xs className={classes.backHomeAlign}>
              <Link to="/register/step2" className={classes.backHomeLink}>
                Back to previous
              </Link>
            </Grid>
          </Grid>
        </form>

I've tried writing one function and including these two, a promise function and generally putting them in other functions/hooks. Nothing works. Any hep much appreciated.

EDIT: I added the relevant code in the return statement. The form, in Step Three is supposed to send the uploaded picture and date of birth input. With this code it send the uploaded picture and but not the date of birth.



Solution 1:[1]

I switched this:

const handleUserInfo = () => {
const updatedUserInfo = {
  dob: selectedDate
};
updateUser(updatedUserInfo);

history.push('/');

};

To that and it worked:

  const updatedUserInfo = {
    dob: selectedDate
  };
  updateUser(updatedUserInfo);

Meaning I had too many OnClick events.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1