Home > Enterprise >  In React, why does my website crash when I type too fast in the TextField?
In React, why does my website crash when I type too fast in the TextField?

Time:02-01

In my app, when I type too fast into the TextField, my website crashes and I see a blank white screen.

Here is the code.

TextField Code:

<TextField
            label="Item name"
            variant="filled"
            required
            color="primary"
            onChange={handleItemNameChange}
            id={`${id}`}
            defaultValue={items[id][0]}
/>

handleItemNameChange:


const handleItemNameChange = (event) => {
    let index = event.currentTarget.id;
    setItems((items) => {
        const tempItems = \[...items\];
       tempItems\[index\]\[0\] = event.currentTarget.value;
       return tempItems;
});
};

The console error I get is as follows when I type too fast:

Uncaught TypeError: Cannot read properties of null (reading 'value')

This error comes from the line: tempItems[index][0] = event.currentTarget.value;

This issue only comes up when I type quite fast into the TextField.

Would greatly appreciate any help in solving this issue!

This issue does not come when I type slowly into the TextField and only occurs when I type a little fast into it. I feel it has something to do with the setItems hook as the Items array gets updated quite often?

CodePudding user response:

The function passed to setItem is not executed immediately, and by the time it is, it might be that the browser reused the event object for something else. You should store event.currentTarget.value in a variable outside of that function, just like you do with index.

CodePudding user response:

"value is undefined", I don't see a value attribute anywhere.

  • Related