Reactjs Handle State Change – Cannot read property of undefined

I am updating initial state based on onchange event passed by textboxes to event handler , as below –

import React,{useState} from 'react'

function ViewAll() {
    const iCandidateState={
        Name:'',
        Age:'',
        Qalification:''
    };
    function nameHandler(event){
        alert(event.target.value);
        this.iCandidateState.Name=event.target.value;
    }
    return (
        <div>
            <table>
              <tr>
                  <td>
                      Name
                  </td>
                  <td>
                      <input type="text" name="txtName" value={iCandidateState.Name} onChange={(e)=>nameHandler(e)}></input> 
                  </td>
              </tr>
              <tr>
                  <td>
                      Age
                  </td>
                  <td>
                      <input type="text" name="txtAge"></input> 
                  </td>
              </tr>
              <tr>
                  <td>
                      Qalification
                  </td>
                  <td>
                      <input type="text" name="txtQualification"></input> 
                  </td>
              </tr>
              <tr>
                  <td colSpan="2" align="center">
                     <button name="btnSubmitForm">Post</button>
                  </td>
              </tr>
            </table>
        </div>
    )
}

export default ViewAll

When I type something in txtName , I expect state – iCandidateState to get updated with Name field within textbox. But I am getting an error – TypeError: Cannot read property 'iCandidateState' of undefined

I also tried this with setState as –

 this.setState({
                ...iCandidateState,
                Name:event.target.value
            })

After typing something in textbox I get error as –

TypeError: Cannot read property 'setState' of undefined

How can I update the state ?

Answer

You have mixed up the idea of class components and functional components. The this syntax is for class components, i.e.

class ViewAll extends Component {

  render() {
    return (/* some components */);
  }
}

You are trying to create a functional component (denoted by the keyword function). So you should use hooks instead. It should be something like

import { useState } from 'react'

function ViewAll() {
  const [iCandidateState, setICandidateState] = useState({
    Name: '',
    Age: '',
    Qalification: ''
  });

  function nameHandler(event) {
    alert(event.target.value);
    setCandState({ ...iCandidateState, Name: event.target.value })
  }

  return (/* some components */);
}

export default ViewAll