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

Advertisements

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’)

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.

Leave a ReplyCancel reply