I want to search items through a search bar.The original items are in prod.but I keep getting startsWith() not a function and sometime .toLowerCase() is not a function
const [prod, setprod] = React.useState([]);
const [getFiltered, setFiltered] = React.useState([]);
const [getSearch,setSearch]=React.useState("");
const SearchItem=(text)=>{
if(text!=""){
const searched=prod.filter((item)=>{
const datachange=item.toLowerCase();
const textchange= text.toLowerCase();
return datachange.startsWith(textchange);
});
setFiltered(searched);
setSearch(text)
}
else{
setFiltered(prod);
setSearch(text);
}}
I agree with @lucasvw that more information would be helpful here.
However, your conditional is only validating that text!="", but if text is something else, like a number, function, or (more likely) undefined or null, this will throw.
I'd recommend changing to something like this:
if (typeof text === "string" && text != "") {
# the rest of your code
}
EDIT:
Sorry, it's actually item that's throwing.
Same idea, but try this instead:
const searched=prod.filter((item)=>{
if (typeof item !== "string") {
return false;
}
const datachange=item.toLowerCase();
const textchange= text.toLowerCase();
return datachange.startsWith(textchange);
});