Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: Object is possibly 'null' by get the input value with html element id

I code with next.js a login:

import type { NextPage } from 'next'
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Router from 'next/router'
import * as React from 'react'

const Home: NextPage = () => {

  const [disable, setDisable] = React.useState(false);

  const loginUser = async (e: any) => {
    try {

      setDisable(true)

      const y = (window.document.getElementById('inputUsername'))

      let inputValue = window.document.getElementById('inputUsername').value

      console.log(inputValue)

      const resp = await fetch('/api/token/valid')
      const data = await resp.json()
      if (data.token) {
        //Router.push('/dashboard')
        setDisable(false)
      }
    } catch (err) {
      // Handle Error Here
      console.error(err);
    }
  };

  return (
    <div className={styles.container}>
      <Head> 
        <title>Login - Uhrenlounge CMS</title>
        <meta name="description" content="Generated by create next app" />
      </Head>

      <main className={styles.main}>
        <form className="p-3 mb-2 bg-secondary text-white">
            <div className="text-center">
                <h1>Uhrenlounge CMS</h1>
            </div>
            <hr />
            <div className="mb-3">
                <label className="form-label">Benutzername</label>
                <input 
                  type="text" 
                  className="form-control" 
                  id="inputUsername" 
                  name="inputUsername" 
                  placeholder="Benutzername" 
                  required 
                  />
            </div>
            <div className="mb-3">
                <label className="form-label">Passwort</label>
                <input type="password" className="form-control" id="inputPassword" placeholder="Passwort" />
            </div>
            <div className="d-grid gap-2">
                <button type="button" disabled={disable} onClick={loginUser} className="btn btn-primary" id="btnLoginUser">Login</button>
            </div>
        </form>
      </main>
    </div>
  )
}

export default Home

I want to get the value of inputs after the click on the button.
I try to get the value with this code:

let inputValue = window.document.getElementById('inputUsername').value

VSCode give me this error: Object is possibly ‘null’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t know what can i do. Does anyone have any idea or explanation how to access the value after onclick?

>Solution :

It’s just telling you that if there is no element with id ‘inputUsername’ getElementById will return null instead of the value you are expecting.

You can handle or ignore that case as you see fit.

However if you really need to access dom nodes in react the right way to do it is hooks https://reactjs.org/docs/hooks-intro.html. Right now your component may not work if two exist at the same time due to the overlapping ids.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading