I've got an error using react-hook-form; TypeError: Cannot read properties of null (reading 'formState')

Viewed 33

I'm a react-hook-form newbie and have got an error below
TypeError: Cannot read properties of null (reading 'formState')

Is there anyone who has faced an error like this? then please help me!

import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { ErrorMessage } from '@hookform/error-message';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { submitStep1 } from 'features/formSlice';

import Text from 'components/Element/Text';
import styled from 'styled-components';
import Input from 'components/Element/Input/Input';
import Button from '@mui/material/Button';

function ProgramName() {
  const {
    register,
    handleSubmit,
    errors,
    formState: { isSubmitting },
  } = useForm({
    defaultValues: '',
  });
  const dispatch = useDispatch();
  const history = useHistory();
  const programName = useSelector((state) => state.programName);

  const [programNameValue, setProgramNameValue] = useState('');

  const handleOnSubmit = () => {
    sessionStorage.setItem('programName', programNameValue);
    dispatch(submitStep1(programNameValue));
    history.push('./step2');
  };
  return (
    <form onSubmit={handleSubmit(handleOnSubmit)}>
      <Text size={30} weight={800} mb={10}>
        Step 1. Program name
      </Text>
      <label htmlFor="programName">Program Name</label>
      <InputBox
        name="programName"
        {...register('programName', { required: 'This is required' })}
        value={programName}
        onChange={(e) => setProgramNameValue(e.target.value)}
      />
      <ErrorMessage errors={errors} name="programName" as="p" />
      <Button type="submit" disabled={isSubmitting}>
        next
      </Button>
    </form>
  );
}

const InputBox = styled(Input)`
  margin-top: 20px;
`;

export default ProgramName;

I'm trying to make wizard form and the above is one of the form components I'm currently using react-hook-form.

1 Answers

I don't know exactly where it's erroring out but at a glance, errors is supposed to come from formState --

const {
  register,
  handleSubmit,
  formState: { isSubmitting, errors },
} = useForm({ defaultValues: '' });

does updating that fix the error?

Related