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

TypeError: Cannot read properties of null (reading 'id') after set state and try to use its value

I have a very simple component:

import {InputText} from 'primereact/inputtext'

const Show = ({id}) => {
  const [item, setItem] = useState(null)

  useEffect(() => {
    itemService
      .getItem(id)
      .then((data) => {
        setItem(data)
        console.log(data)
      })
  }, [])

  return (
    <InputText id='firstname' type='text' value={item.id} />
  )
}

When I start server I get the error:

Server Error TypeError: Cannot read properties of null (reading ‘id’)

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

When I remove value={item.id} from return part, the error is fixed and it shows that itemService successfully executed and console.log(data) return desired value as:

{
  "id": 1,
  "createdAt": "2023-05-15T16:44:30.808+00:00",
  "enabled": true
}

Although I set the item state inside useEffect hook, why I get null value for item? and how can I fix this?

>Solution :

The initial value is null:

const [item, setItem] = useState(null)

That value may indeed change at some later time. But on the first render of the component that value is explicitly defined as null.

Then you try to read a property from that value:

return (
  <InputText id='firstname' type='text' value={item.id} />
)

As the error states, you can’t read id on null. You can use optional chaining:

return (
  <InputText id='firstname' type='text' value={item?.id} />
)

Or perhaps not render at all until there’s a value:

return (
  item === null ? null : <InputText id='firstname' type='text' value={item.id} />
)

Or, taking a different approach entirely, you can initialize to something other than null:

const [item, setItem] = useState({})

There are a variety of approaches, whatever fits your needs is fine. The only approach that isn’t fine is trying to de-reference a property on null.

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