I’m trying to create a component on my site that shows “Similar items” a user may want to see. When I pull in this component, I pass an array through search
ex. search = [‘bmw’, ‘suspension’, ‘springs’]
I set a limit of how many results I want (ex. 5) and then have the component grab listings based on each tag starting with the first. If BMW only returns 2 items, then it should search for suspension and limit it’s return count to 3 until the limit of 5 listings has been met. In the for loop, I’m trying to track how many listings have already been pulled and adjust the query limit accordingly but I always get a length of 0 in the loop. See console log below.
import { useEffect, useState } from 'react'
import ListingTile from '@components/listing/ListingTile';
const ListingGrid = ({search, activeItem, limit = 5}) => {
const [listings, setListings] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchListing();
}, [search])
const fetchListing = async () => {
//set search array has been passed
if (search.length > 0) {
for(let i = 0; i < search.length; i++) {
//stop searching for similar items if limit has been reached.
if(listings.length === limit){
break;
}
console.log(listings.length) //ALWAYS RETURNS 0
//limit results to limit - the items already in the listing state.
const response = await fetch('/api/listing?limit=' + parseInt(limit-listings.length) + '&search=' + search[i]);
let data = await response.json();
//don't show the current item user is viewing if returned in results
if(activeItem && data.listings){
data.listings = data.listings.filter((item) => {
return item._id !== activeItem
})
}
//push listings to state and continue till limit has been reached
setListings([...listings, ...data.listings]);
}
}
setLoading(false);
}
return (
<>
{loading ? (
<div className="grid-container grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-6">
<div className="skeleton h-48 sm:col-span-1 rounded-none"></div>
<div className="skeleton h-48 sm:col-span-1 rounded-none"></div>
<div className="skeleton h-48 sm:col-span-1 rounded-none"></div>
<div className="skeleton h-48 sm:col-span-1 rounded-none"></div>
</div>
) : (
<div className='grid-container grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-6 mb-6'>
{(listings.length > 0) && listings?.map((listing) => (
<ListingTile key={listing._id} listing={listing} />
))}
</div>
)}
</>
)
}
export default ListingGrid