简体   繁体   中英

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;

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM