I want to send a request to the api when the input changes in react native, but I want to send a request 500 milliseconds after the end of the typing, not every time a word is written to the input. But I'm having a little problem, every time I type text, lodash is also triggered.
import { debounce } from "lodash";
import React, { FC, useState } from "react"
import { TextInput, View } from "react-native"
interface Props {
}
const LodashInputComponent: FC<Props> = (props) => {
const [searchText, setSearchText] = useState("");
const onDebounceSearch = debounce((value: string) => {
console.log("API Send request", value);
}, 500);
const onChangeSearchText = (val: string) => {
console.log("Change search text", val);
setSearchText(val);
onDebounceSearch(val);
};
return (
<View>
<TextInput
value={searchText}
onChangeText={onChangeSearchText}
placeholder="Search"
/>
</View>
)
}
export default LodashInputComponent;
Change search text h
Change search text he
API Send request h
API Send request he
Change search text hel
Change search text hell
API Send request hel
Change search text hello
API Send request hell
API Send request hello
Change search text hello
Change search text hello w
Change search text hello wo
API Send request hello
API Send request hello w
Change search text hello wor
API Send request hello wo
API Send request hello wor
Change search text hello worl
Change search text hello world
API Send request hello worl
API Send request hello world
I installed the Lodash library, I prepared my input component, I wrote my functions, I just want to see the API Send console log correctly, not continuously.
You must define your debounce function out from component.
Here is your modified code:
import { debounce } from "lodash";
import React, { FC, useState } from "react"
import { TextInput, View } from "react-native"
interface Props {
}
// Moved out from component
const onDebounceSearch = debounce((value: string) => {
console.log("API Send request", value);
}, 500);
const LodashInputComponent: FC<Props> = (props) => {
const [searchText, setSearchText] = useState("");
const onChangeSearchText = (val: string) => {
console.log("Change search text", val);
setSearchText(val);
onDebounceSearch(val);
};
return (
<View>
<TextInput
value={searchText}
onChangeText={onChangeSearchText}
placeholder="Search"
/>
</View>
)
}
export default LodashInputComponent;
If require to dispatcher to dispatch
your action of redux, same pass callback function
or send dispatch as params
of onDebounceSearch
like:
const onDebounceSearch = debounce(callback: () => void) => {
callback()
}, 500);
onChangeSearchText:
const onChangeSearchText = (val: string) => {
console.log("Change search text", val);
setSearchText(val);
onDebounceSearch(() => {
console.log("API Send request", val);
});
};