Search code examples
reactjscrudmern

How to return all Products if query doesn't exist?


I'm almost finished with my website, I've got a problem with the query. I can already search for the name of the product.

But I want to render all the products if the searched name isn't found.

import { Box } from '@mui/material'
import React from 'react'
import { useState } from 'react'
import { useEffect } from 'react'
import { publicRequest } from '../requestMethod'
import CardProduct from './CardProduct/CardProduct'

const ProductListAfterSearch = ({query}) => {
  const [selectedProduct, setSelectedProduct] = useState([])

  console.log(query)

  useEffect(() => {
    const getProducts =  async () => {
      const res = await publicRequest.get(query ? `/products/search?searchQuery=${query}` : 'http://localhost:5000/api/products/')
      setSelectedProduct(res.data)
    }
    getProducts()
  }, [query])



  return (
    !selectedProduct.length? 'Product do not exist......': 
    <Box sx={{display: 'flex', flexWrap: 'wrap', gap: {xs: '0px', md: '10px'}, justifyContent: 'center'}}>
      {selectedProduct.map((product) => (
        <CardProduct query={query} key={product._id}  product={product}/>
      ))}
    </Box>
  )
}

export default ProductListAfterSearch

ParentChild/SearchProduct.js

const SearchedProducts = () => {

  const location = useLocation()
  const query = location.pathname.split('/')[2]

  
  return (
    <Box>
        <Navbar />
        <Sidebar  />
        <ProductListAfterSearch query={query}  />
        
    </Box>
  )
}

This is what it looks like when searched not found


Solution

  • How about you try something like this:

    useEffect(() => {
        const getProducts =  async () => {
        let res = await publicRequest.get(query ? `/products/search?searchQuery=${query}` : 'http://localhost:5000/api/products/')
        if(res.data.length === 0) {
           res= await publicRequest.get('http://localhost:5000/api/products/');
        }
      setSelectedProduct(res.data)
      }
      getProducts()
    }, [query])
    

    You do the search with the query, if it returns 0 results you then search again for all products.

    Although ideally you would handle it in the backend. In the same way as I checked here if there are 0 results, you could do that in your service and if its 0, just return all. That would save you a second trip to the server and would be more efficient