4

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

2
  • Are you sure that event and event.target contain values? Error sounds like event.target is null Commented Feb 6, 2020 at 15:25
  • Yes the values aren't null. Robbies solution worked and it makes absolutely sense. Double checked the event.target.value Commented Feb 6, 2020 at 15:33

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

1 Comment

I had the same exact problem. calling setState() directly from onChange() and it worked on 95% of the fields until it failed on 1 field. I guess I've must have been lucky with the other ones :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.