in useEffect
hook i used a function to send request to api for search. function name is searchCharacters
and it is outside of component. i get error TypeError: searchCharacters(...) is undefined
when my code excuted on that point. why? how can in fix this?
function Dashboard() {
const [searchParam, setSearchParam] = useState("");
const [results, setResults] = useState([]);
const [isSearching, setIsSearching] = useState(false)
const debouncedSearchTerm = useDebounce(searchParam, 500);
useEffect( ()=> {
if(debouncedSearchTerm){
setIsSearching(true);
searchCharacters(debouncedSearchTerm).then(res => {
setIsSearching(false);
console.log("im search result", res);
setResults(res);
});
}else{
setResults([]);
}
}, [debouncedSearchTerm]);
}
function searchCharacters(search){
api.get(`client/search?q=${search}`).then(
(res) => {
return res.data;
}
).catch( e => {
console.log(e);
return [];
})
}
export default Dashboard;
searchCharacters
doesn't return a Promise to chain from. Return the api.get
Promise chain from searchCharacters
.
function searchCharacters(search) {
return api
.get(`client/search?q=${search}`)
.then((res) => {
return res.data;
})
.catch((e) => {
console.log(e);
return [];
});
}
Or slightly more succinct
const searchCharacters = (search) =>
api
.get(`client/search?q=${search}`)
.then((res) => res.data)
.catch((e) => {
console.log(e);
return [];
});
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.