darkace darkace - 1 day ago 4
Javascript Question

Debouncing not working with React-Redux app

I'm building a function that performs an API request on keypress, but I want this debounced.

This doesn't currently work and produces an error:

lodash.js:10319 Uncaught TypeError: Expected a function


Here's a code snippet with a console log instead of async request, which also doesn't work!

import React from 'react';
const _ = require('lodash');

const method = () => {
return _.debounce(testFunc(), 3000);
};

const testFunc = () => {
console.log('echo echo test test');
};


const SearchBox = ({ onTypingSearch, searchTerm }) => (
<form>
<p>Search: {searchTerm}</p>
<input
onChange={(e) => {
console.log(e.target.value);
onTypingSearch(e.target.value);
console.log(method);
method();
}}
value={searchTerm}
/>
</form>
);

export default SearchBox;

Answer

You have to debounce the function, not the result of calling it:

This:

const method = () => {
    return _.debounce(testFunc(), 3000);
};

To this:

const method = () => {
    return _.debounce(testFunc, 3000);
};

Update:

The way you have set this up, method returns a debounced function. So calling method() will return a function. Then you will have to call it: method()().

It is better to do this:

const method = _.debounce(() => {
    return testFunc();
}, 3000);

And if you want args:

const method = _.debounce((e) => {
    return testFunc(e);
}, 3000);

Then, you can continue calling the way you are doing at the moment: method().

Comments