Home > Software engineering >  TypeScript : Object is possibly 'null' useRef
TypeScript : Object is possibly 'null' useRef

Time:12-10

after submitting the form I want to clean the input using useRef. In function handleFormSubmit, after sending the value I am assigning emailRef.current.value to the empty string and I have an error Object is possibly 'null'. For clarity, I cannot add an optional operator because the left-hand side of an assignment expression cannot be optional. Please help ;)

const emailRef = useRef<HTMLInputElement | null>(null);

  const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    setEmail(emailRef.current?.value);
    return onValidated({ EMAIL: email || '' }), alert('Zapisano!'), (emailRef.current.value = '');
  };

          
<input
            ref={emailRef}
            type="email"
            placeholder="e-mail"
            className="font-medium max-w-full px-5 py-5 mr-2 rounded-md border-2 border-emerald-dark transition-all"
          />

CodePudding user response:

Add an if statement,

const emailRef = useRef<HTMLInputElement | null>(null);

const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    setEmail(emailRef.current?.value);

    if (emailRef.current) {
      emailRef.current.value = ''
    }


    return onValidated({ EMAIL: email || '' }), alert('Zapisano!');
  };
          
<input
  ref={emailRef}
  type="email"
  placeholder="e-mail"
  className="font-medium max-w-full px-5 py-5 mr-2 rounded-md border-2 border-emerald-dark transition-all"
/>

CodePudding user response:

You either need to write code which checks for null and thus proves to typescript that the assignment is safe:

if (emailRef.current) {
  emailRef.current.value = '';
}

Or if you know for a fact it's impossible for it to be null, you could use a non-null assertion. Be aware that if you do this, typescript will not check your work, so if you use it when it actually can be null, you will get a runtime error.

emailRef.current!.value = '';
  • Related