Home > Blockchain >  React Filter not returning data if search is empty
React Filter not returning data if search is empty

Time:06-19

my problem is data not showing up if searchterm is empty.

this used to work with my old json data if (!searchTerm) return data. but now I'm using sanity cdn and I'm not sure why this isn't working. also this is a new warning in the console log.

React Hook useMemo has a missing dependency: 'data'. Either include it or remove the dependency array.


const [data, setData] = useState([] as any [])

  useEffect(() => {
  sanityClient.fetch(`*[ _type == "positions"] {
        _id,
        category,
        type,
        position,
        location,
    }`
    ).then(result => {
    setData(result)
  })
}, [])

    const [searchTerm, setSearchTerm] = useState<string>("");

    const filteredPositions = useMemo(() => {
        if (!searchTerm) return data;
        return data.filter(({ id, ...other }) => {
            const lowerCasedSearchTerm: string = searchTerm.toLowerCase();

            return Object.values(other)
                .map((v: any) => v.toLowerCase())
                .some((v: any) => v.includes(lowerCasedSearchTerm));
        });
    }, [searchTerm]);

     {filteredPositions?.map((position: any, index) => (
                        <div key={position.position}>
                            <SinglePosition
                                category={position.category}
                                type={position.type}
                                position={position.position}
                            />
                        </div>
                    ))}

CodePudding user response:

Data from Sanity is fetched asynchronously, so your component is at first render with an empty array as data.

Then you are using useMemo hook with searchTerm as the only dependency. This mean, that this part of website would rerender only if searchTerm is changed. But you want it to render again when data is fetched form Sanity as well.

To do that you should update dependency array of useMemo hook by adding data to it

const filteredPositions = useMemo(() => {
  // ...
}, [searchTerm, data]);
  • Related