Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  64] [ 7]  / answers: 1 / hits: 6883  / 4 Years ago, mon, august 31, 2020, 12:00:00

I'm trying to debounce text input field change with Lodash's debounce function.


import React from "react";
import debounce from 'lodash.debounce';

const Input = () => {

const onChange = debounce((e) => {
const { value } = e.target;
console.log('debounced value', value)
}, 1000)

return (

<input type="text" onChange={ onChange } />

)
};

The code above throws the following errors:



Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().




Uncaught TypeError: Cannot read property 'value' of null



What is the correct implementation?


More From » reactjs

 Answers
5

When to Use Refs There are a few good use cases for refs:



  • Managing focus, text selection, or media playback.

  • Triggering imperative animations.

  • Integrating with third-party DOM libraries.


Avoid using refs for anything that can be done declaratively.



Refs and the DOM


The way you defined Input, I am assuming it would be used in many places. So, I would do this:


import React from "react";
import debounce from 'lodash.debounce';

const Input = () => {

// Debounced function
// `printValue` only cares about last state of target.value
const printValue = debounce(value => console.log(value), 1000);

// Event listener called on every change
const onChange = ({ target }) => printValue(target.value);

return <input type="text" onChange={ onChange } />;

};

[#2777] Wednesday, August 26, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
Tue, May 26, 20, 00:00, 4 Years ago
;