React: Error Returning Value in Arrow Function

BLUF: I checked this similar Stack Overflow: React JSX error expected a return value at the end of the arrow function, followed the advice, and still have the same problem

I get the warning Array.prototype.filter() expects a value to be returned at the end of arrow function and my local host server is loading endlessly as a result.

Here is my code:

import JSONDATA from './MOCK_DATA.json';
import "./Navbar.css";
import {useState} from 'react'

const Searchbar = () => {
    const [searchTerm, setSearchTerm] = useState('')
    return (
        <div className="Search">
            <input type="text" placeholder="Search..." onChange={event => {setSearchTerm(event.target.value)}}/>
            {JSONDATA.filter((val) => {
                if (searchTerm === "") {
                    return ''
                } else if (val.first_name.toLowerCase().includes(searchTerm.toLowerCase())) {
                    return val
                }

            }).forEach((val, key) => {
                return (
                    <div className="user" key={key}>
                        <p>{val.first_name}</p>
                    </div>
                );
            })}
        </div>
    );
}

export default Searchbar

Answer

Array.prototype.filter() expects a value to be returned at the end of arrow function

The error means exactly what it says. It’s possible that the function you passed to filter doesn’t return a response (if neither of your if conditions are true), which is invalid.

Additionally, the function passed to filter should be returning a true or false response. Technically you’re trying to do that because '' is falsy and an object is truthy. But that’s probably not what you meant to do.

If this is the condition you’re checking in your filter:

if (val.first_name.toLowerCase().includes(searchTerm.toLowerCase()))

Then just check that condition:

JSONDATA.filter(val => val.first_name.toLowerCase().includes(searchTerm.toLowerCase()))

Assuming none of these properties are null or undefined, includes() will return a true or false value. If they might be null or undefined, you’ll want to add checks for that as well.


Additionally, you appear to be misusing forEach here. forEach is for looping over an array to perform an operation on each element. map is for projecting an array into a new array, transforming each element. You appear to be wanting the latter, so replace the forEach with map.