0

I have a giant form, and it's setup so that the handleChange method changes the state values of the data as the user types. I then want it to write to the mySql database, which I can also do, except currently, it writes after every keypress. I'm trying to figure out how to wait a few seconds after input stops, so that it doesn't do it after every single key press.

handleChange(e) {
        const targetName = e.target.name;
        const targetValue = e.target.value
        this.setState({
            [e.target.name]: e.target.value
        });
        console.log(`${targetName}: ${targetValue}`);

       /// I want a timer here that will only move on if input has stopped for a few seconds.

        /// Call to my database query will be here
    }
Adam Norton
  • 512
  • 2
  • 5
  • 21
  • this is generally referred to as a debounce, or a throttle, depending on the specifics of how you want the timer to function. – Kevin B Aug 26 '20 at 19:04
  • Does this answer your question? [Perform debounce in React.js](https://stackoverflow.com/questions/23123138/perform-debounce-in-react-js) – Kevin B Aug 26 '20 at 19:06
  • https://stackoverflow.com/a/44212683/10028748 – WilTree Aug 26 '20 at 19:21

1 Answers1

0

For anyone who wants the answer that I used, I put it together from the link that @WilTree posted above.

let timeout;

class General extends Component {
    constructor(props) {
        super(props);

        this.state = {
            typing: false,
            typingTimeout: 0,

            organization: "",
            address: "",
            website: "",
            industry: "",
            status: ""
        };

        this.handleChange = this.handleChange.bind(this);
    

    }


    handleChange(e) {
        const targetName = e.target.name;
        const targetValue = e.target.value
        this.setState({
            [e.target.name]: e.target.value
        });
        if (this.state.typingTimeout) {
            clearTimeout(this.state.typingTimeout);
        }

        this.setState({
            typing: false,
            typingTimeout: setTimeout(function () {
                console.log(`${targetName}: ${targetValue}`);
            }, 3000)
        });
        
    }
Adam Norton
  • 512
  • 2
  • 5
  • 21