I'm trying to create a search function, I'm following the code from https://www.freecodecamp.org/news/how-to-react-components/ Note that I'm using my own "API" and not the one freecodecamp uses. However I get an error that reads: Cannot read properties of undefined (reading 'toString') What could be the cause of this
Here's my code, it's identical only difference is the fetch URL.
import React from 'react'
import { useEffect } from 'react';
import { useState } from 'react';
function Main() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
const [query, setQuery] = useState("");
const data = Object.values(items);
const search_parameters = Object.keys(Object.assign({}, ...data));
// const search_parameters = ["title", ...data]
function search(data) {
return items.filter(
(item) =>
search_parameters.some((parameter) =>//Error here
item[parameter].toString().toLowerCase().includes(query)
)
);
}
useEffect(() => {
fetch('http://localhost:3005/movies')
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<>
<input
type="search"
name="search-form"
id="search-form"
className="search-input"
placeholder="Search for..."
onChange={(e) => setQuery(e.target.value)}
/>
<div className='card-wrapper'>
{search(data).map((item)=>(
<div className="movie-card">
<p className="title">{item.title}</p> <br></br>
<img src={item.cover} className="card-img"/> <br></br>
</div>
))}
</div>
</>
);
}
}
export default Main
Propably there is problem in line:
item[parameter].toString().toLowerCase().includes(query)
There is no property named parameter (it should be named property) on your item object, therefore undefined has no toString() method. To fix this issue, you should check if such property exists first.
...
if (parameter in item) {
return item[parameter].toString()
.toLowerCase()
.includes(query);
}
...