Skip to content
Advertisement

Apply filters to a list and show data

Front-end:

 const [searchParameters, setSearchParameters] = useState({
    type: "",
    country:"",
    
  });

  const onChangeSearchType = e => {
    const workingObject = {...searchParameters};
    workingObject.searchType = e.target.value; 
    setSearchParameters(workingObject);   
  };

  const onChangeSearchCountry = e => {
    const workingObject = {...searchParameters};
    workingObject.searchCountry = e.target.value; 
    setSearchParameters(workingObject);
  };


const handleFetchWithSearchParameters = () => {
    TutorialDataService.findByParameters(searchParameters)       
      .then(response => { 
        setTutorials(response.data); 
        console.log(response.data);       
      })       
      .catch(e => { 
        console.log(e);       
      });  
  }

After return():

<Form.Control as="select" defaultValue=""
            type="text"
            className="form-control"
            id="country"
            required
            value={searchParameters.country}
            onChange={onChangeSearchCountry}
            name="country">
            <option>Nigeria</option>
            <option>Ghana</option>
            <option>Kenya</option>
            <option>Senegal</option>
                 </Form.Control>
                 <Form.Control as="select" defaultValue=""
            type="text"
            className="form-control"
            id="type"
            required
            value={searchParameters.type}
            onChange={onChangeSearchType}
            name="type">
            <option>Agricultural</option>
            <option>Manufacturing</option>
            <option>Industrial</option>
            <option>Livestock</option>
            <option>Service Industry</option>
                 </Form.Control>
 <div className="input-group-append">
<button 
className="btn btn-outline-secondary" 
type="button" 
onClick={handleFetchWithSearchParameters}
       Search 
</button>

Service.js:

import http from "../http-common.js";
const findByParameters = searchParameters => {
  // This is the destructuring syntax I've linked above
  const { type, country, creditscore, interest } = searchParameters;

  // Here we use & ampersand to concatinate URL parameters
  return http.get(`/tutorials?type=${type}&country=${country}&creditscore=${creditscore}&interest=${interest}`); 
}; 

export default {
 
  findByParameters
};

Controller.js:

// Retrieve all Industries from the database.
exports.findAll = (req, res) => { 
const type = req.query.type ; 
let condition = type ? { type : { [Op.like]: %${type }% } } : null;

Tutorial.findAll({ 
where: condition, 
order: [   ['createdAt', 'DESC'] ] 
})     
.then(data => { res.send(data);     
})     
.catch(err => { 
res.status(500).send({ message:err.message || "Some error occurred while retrieving tutorials."
       });     
}); };

So, this page of my web-app serves to show a list of all the companies saved in my database.

I created a filter that allows you to show only those of a certain type, via findByType.

I would like to insert other filters such as: findByRevenue, findByEmployeesNumber.

I don’t know if should I write new functions in both front-end and back-end for each case? Or is there a smarter method?

Also, filters don’t have to work individually, they also need to be combined together to improve your search. I hope I have explained well how it should work, it is like any e-commerce site.

EDIT: I changed the code as it was suggested to me, but I still have problems. It no longer makes me use input forms. In fact the requests are empty ex:

type = ""
country = ""

I think I have something wrong in input.value =

Advertisement

Answer

Just an opinion: I would slightly modify both the front-end and the back-end to support combined requests. You can send a JavaScript Object (as JSON) to your API with different parameters and apply checks in the back-end controller function.

So basically, instead of separate

 const findByType = () => {...}
    const findByRevenue = () => {...}
    const findByEmployeesNumber = () => {...}
   

I would use (the state can be a monolithic object like in the example below, or separated and then assembled into an Object when sent to the API)

   const [searchParameters, setSearchParameters] = useState({
        type: '',
        revenue: '',
        employeesNumber: ''
      });
    
    const onChangeSearchType = e => { 
      const workingObject = {...searchParameters};
      const workingObject.searchType = e.target.value; 
      setSearchParameters(workingObject);   
    };
    
    // same logic for onChangeRevenue and onChangeEmployeesNumber
    
    const handleFetchWithSearchParameters = () => {
      TutorialDataService.findByParameters(searchParameters)       
        .then(response => { 
          setTutorials(response.data); 
          console.log(response.data);       
        })       
        .catch(e => { 
          console.log(e);       
        });  
    }

And then in the controller, I would destruct the query Object and run queries against it

Advertisement