Drico
Drico

Reputation: 1360

Weird setState behaviour with MaterialUI in React JS

I'm trying to show an input component from material-ui, but when I write some text (something like 3 letters), the page crashes.

import React from 'react';
import Input from '@material-ui/core/Input';

export default function ComposedTextField() {
  const [state, setState] = React.useState('');

  const handleChange = event => {
    setState((state) => event.target.value);
  };

  return (
    <Input id="component-simple" value={state} onChange={handleChange} />
  );
}

I've noticed that replacing setState((state) => event.target.value); with setState(event.target.value); fixes the issue, but I need (in my real project) to use the full version of setState.

Does anybody understand why the setState((state) => event.target.value); doesn't work ?

Upvotes: 1

Views: 333

Answers (1)

cbr
cbr

Reputation: 13652

The event object is re-used after the callback has run, so it cannot be used asynchronously like what the code does right now.

Grab whatever values you need out of the event into their own variables:

const handleChange = event => {
  const { value } = event.target
  setState((state) => value);
};

Alternatively if you need access to the whole event, you can use event.persist() to remove the object from the pool and not have it re-used.

Upvotes: 7

Related Questions