Trying to create a delay on react component that has input field that updates on change.
Here's the code:
import React from 'react';
import Input from "@material-ui/core/Input";
import {debounce} from "lodash";
...
const SampleRow = () => {
let [newFriend, setNewFriend] = React.useState({name: '', lastSeen: '', contactIn: ''});
const onAddFriend = debounce(() => {
if(newFriend.name.length === 0){
return;
}
console.log(newFriend.name);
}, 2000);
return (
<TableRow>
<TableCell component="th" scope="row">
<Input
value={newFriend.name}
onChange={(event) => {
setNewFriend({...newFriend, name: event.target.value});
onAddFriend();
}}
placeholder={"Add friend"}
disableUnderline={true}
/>
</TableCell>
<TableCell align="left">{newFriend.lastSeen ? newFriend.lastSeen : ''}</TableCell>
<TableCell align="left">{newFriend.contactIn ? newFriend.contactIn : ''}</TableCell>
<TableCell align="left" className={classes.externalLinks}/>
</TableRow>
)
};
What happens is that the console.log
prints out every change (after the timeout of 2s), and won't cancel the previous triggers.
The question is why is that happens? and how could this could be solved?
I've found similar questions with complex
useDebounce
logic or class-components. Didn't find a reference for this problem.