currently I am working on a Search Component in ReactJS. In this case I get an "TypeError: Cannot read properties of undefined (reading 'toString')" - Error, while trying to display it on localhost:3000.
If I remove the [newItem], there would not be thrown an error. It would be very cool, if someone could help.
Mainly the problem is the function search(items)..
function App() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
const [q, setQ] = useState("");
const [searchParam] = useState(["capital", "name"]);
useEffect(() => {
fetch("URL")
.then((res) => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
(error) => {
setIsLoaded(true);
setError(error);
}
);
}, []);
function search(items) {
return items.filter((item) => {
return searchParam.some((newItem) => {
return (
item[newItem]
.toString()
.toLowerCase()
.indexOf(q.toLowerCase()) > -1
);
});
});
}
if (error) {
return <>{error.message}</>;
} else if (!isLoaded) {
return <>loading...</>;
} else {
return (
<div className="wrapper">
<div className="search-wrapper">
<label htmlFor="search-form">
<input
type="search"
name="search-form"
id="search-form"
className="search-input"
placeholder="Search for..."
value={q}
onChange={(e) => setQ(e.target.value)}
/>
<span className="sr-only">Search countries here</span>
</label>
</div>
<ul className="card-grid">
{search(items).map((item) => (
<li>
<article className="card" key={item.callingCodes}>
<div className="card-image">
<img src={item.flag} alt={item.name} />
</div>
<div className="card-content">
<h2 className="card-name">{item.name}</h2>
<ol className="card-list">
<li>
population:{" "}
<span>{item.population}</span>
</li>
<li>
Region: <span>{item.region}</span>
</li>
<li>
Capital: <span>{item.capital}</span>
</li>
</ol>
</div>
</article>
</li>
))}
</ul>
</div>
);
}
}
item[newItem].city