2

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>
    );
}

}

7
  • Is newItem an object? Commented Jan 4, 2022 at 9:41
  • Can you share the items array? Commented Jan 4, 2022 at 9:41
  • Yeah that is most likely an Object. I get some results with index (0, 1, 2) with parameters like a: value, c: value and so on.. I am getting it from my database using the fetch method Commented Jan 4, 2022 at 9:50
  • you are trying to display an object in the UI as a string. 'toString' is expecting a string value. Instead, it got an object. so, it is throwing an error. You try like item[newItem].city Commented Jan 4, 2022 at 9:53
  • Oh fuck yes.. my fault.. Would it be possible to just take the values from the Object? I think then I could display it, right? I am not sure, would it go with Object.values()? Commented Jan 4, 2022 at 10:11

1 Answer 1

1

The problem-line of my code was:

item[newItem].toString().toLowerCase().indexOf(q.toLowerCase()) > -1

To "fix" I did this:

item[newItem]?.toString().toLowerCase().indexOf(q.toLowerCase()) > -1
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.