Home > database >  Create error if search query doesnt provide any results React
Create error if search query doesnt provide any results React

Time:11-05

I have a search component that GETs rows from a MySQL table. It filters out any results that don't match the search query to a table row. I want to show an error if no results were found or show the number of results that were found.

For example: If the users search 'a', they might see '10 results found', 10 being the number of rows in the table that contained 'a'.

I have tried to achieve this using a ternary operator and console logging the variable used as the query (id) of the specific table row (row.name), I haven't been able to find the correct variable to use as the parameter for the ternary operator.

Therefore would like any suggestions on how I can restructure the component to present an error if the user's query doesn't match any rows in the table.

Heres the component

import React, {useState, useEffect} from 'react';
import { useParams } from "react-router-dom";
import Helmet from 'react-helmet';
import axios from 'axios';

export default function Results() {
    //Extracts ID from URL
    const {id} = useParams();
    const [rows, setRows] = useState([]);

    useEffect(() => {
        axios.get('http://localhost:8080/products/get/')
            .then(res => {
                setRows(res.data);
            }).catch(err => {
            console.log(err);
        });
    });

    return (
        <>
            <Helmet>
                <title>website title | {id}</title>
            </Helmet>

            <div >
                <h1 >Showing results for: {id}</h1>

                <div >
                    <div >
                        sidebar
                    </div>

                    <div >
                        <div >
                            <div >Sort by: </div>
                            <div >Product per page:</div>
                        </div>

                        {rows
                            .sort((a, b) => a.name.localeCompare(b.name)) //Sorts alphabetically
                            .filter(row => row.name.toLowerCase().includes(id.toLowerCase())) //Filters matching letters by ID
                            //Maps results
                            .map((row, index) => {
                                return (
                                    <div key={index}>
                                        <p>{row.name}</p>
                                        <img src={row.image} alt="Image of product"  />
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
            </div>
        </>
    );
};

CodePudding user response:

You can save query result to state and filtered rows to object

const [error, setError] = useState(null);

useEffect(() => {
  axios.get('http://localhost:8080/products/get/')
    .then(res => {
      setRows(res.data);
    }).catch(err => {
      console.log(err);
      setError(err);
    });
});

const filteredRows = rows.sort((a, b) => a.name.localeCompare(b.name)) 
                         .filter(row => row.name.toLowerCase().includes(id.toLowerCase()))

return (
  // ...
  <div>{`${filteredRows.length} results found`}</div>
  <div>{error || !rows.length ? 'No data' : filteredRows.map( // ...) }</div>
)
  • Related