Ravi
Ravi

Reputation: 28

How to fix. TypeError: Cannot read property 'user' of null

Am trying to create a copy of the state, update the copy and assign it back to the state but it throws an error.

Here is my code:

class App extends Component {
  constructor(){
    super()
    this.State = {
      user: {
        username: '',
        password: ''
      }
    }
  }
  updateuser = (attr, event) => {
    console.log(attr + '==' + event.target.value);
    let updateduser = Object.assign({}, this.state.user) // errored line
    updateduser[attr] = event.target.value

    this.setState({
      user: updateduser
    })
  }

console error:

App.js:17 Uncaught TypeError: Cannot read property 'user' of null
    at App._this.updateuser (App.js:17)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:265)

Upvotes: 0

Views: 1523

Answers (2)

Tarreq
Tarreq

Reputation: 1365

Just update this.State to this.state

Upvotes: 0

Praveen Rao Chavan.G
Praveen Rao Chavan.G

Reputation: 2860

It's just a typo, change this.State to this.state,

class App extends Component {
  constructor(){
    super()
    this.state = { //fix
      user: {
        username: '',
        password: ''
      }
    }
  }

  updateuser = (attr, event) => {
    console.log(attr + '==' + event.target.value);
    let updateduser = Object.assign({}, this.state.user) // errored line
    updateduser[attr] = event.target.value

    this.setState({
      user: updateduser
    })
  }

Upvotes: 1

Related Questions