Neal Mc Beal
Neal Mc Beal

Reputation: 245

TypeError: Cannot read property 'value' of null in React Form

I'm working on a form where I have an HTML input that just takes numbers or letters. The short form of my state interface is the following:

interface State {
    location: string;
    startDate: Date;
}

I initialize my state like this:

const [state, setState] = useState<State>({
        location: '',
        startDate: new Date(),
    });

My onChangeHandler is the following:

const handleChangeLocation = useCallback((event: ChangeEvent<HTMLInputElement>): void => {
        setState(prevState =>
            update(prevState, {
                location: {$set: event.target.value},
            })
        );
    }, []);

The HTML input is this:

<input id="search-grid-location" className="search-grid-element" type="text"
                           placeholder="Location"
                           onChange={handleChangeLocation}/>

When I write i. e. 1 in the input there is no error but when I write 2, after the first input, the error occurs. The input field contains 12

The error occurs at the location line. See the picture

I debugged the application and the event.target.value holds the input values. So there might be an error with the prevState variable. I use functional components.

I use to update my state the immutability-helper package. Link

Upvotes: 4

Views: 2560

Answers (1)

Robbie Milejczak
Robbie Milejczak

Reputation: 5770

Before you call setState you're going to want to grab the value of event.target.value. By the time setState is executed (especially since you're using functional setState), the React SyntheticEvent will have been cleared, so it's target property will be null.

useCallback((event: ChangeEvent<HTMLInputElement>): void => {
  // do this and your error will go away
  const {value} = event.target;
  setState(prevState =>
    update(prevState, {
      location: {$set: value},
    })
  );
}, []);

read more about the SyntheticEvent

Upvotes: 15

Related Questions