I'm trying to debounce a search in react using lodash, debounce.
But when ever its run I'm receiving a type error
TypeError: Cannot read property 'debounce' of undefined
I have tried moving it around in the code but can't understand why it isn't working
I started off by importing it
import { _, debounce } from 'lodash'
I have an input as following
<input
type="text"
value={this.state.query}
onChange={(e) => {this.updateQuery(e.target.value)}}
placeholder="Search by title or author"
/>
Connected to this function
updateQuery = (query) => {
_.debounce(() => query(this.setState({ query }), 500))
this.onBookSearch(query)
}
Does anyone understand why this is?
I'm trying to debounce a search in react using lodash, debounce.
But when ever its run I'm receiving a type error
TypeError: Cannot read property 'debounce' of undefined
I have tried moving it around in the code but can't understand why it isn't working
I started off by importing it
import { _, debounce } from 'lodash'
I have an input as following
<input
type="text"
value={this.state.query}
onChange={(e) => {this.updateQuery(e.target.value)}}
placeholder="Search by title or author"
/>
Connected to this function
updateQuery = (query) => {
_.debounce(() => query(this.setState({ query }), 500))
this.onBookSearch(query)
}
Does anyone understand why this is?
Share Improve this question asked Jul 27, 2017 at 21:21 Petter ÖstergrenPetter Östergren 1,0135 gold badges16 silver badges29 bronze badges 3-
Sounds like you don't actually have
lodash
in your node_modules. Did you forget tonpm install --save lodash
? – Matthew Herbst Commented Jul 27, 2017 at 21:23 - Hi, yes I do have it. Thanks for checking. The solution below worked – Petter Östergren Commented Jul 27, 2017 at 21:27
-
could you explain what does mean
query( this.setState()..), 500)
in a body of debounce function? – kuka Commented Mar 7, 2019 at 15:46
1 Answer
Reset to default 13I think your import is the problem. You probably want to import the _
as default:
import _, {debounce} from 'lodash';
Also you're not using the extracted function:
updateQuery = (query) => {
debounce(() => query(this.setState({ query }), 500))
this.onBookSearch(query)
}
Since you're extracting {debounce}
in the import you can use it directly.