1

I'm trying to make a filtering system for my website and was wondering how I could filter a GET request by specifying what to filter from the frontend.

Here is what I'm trying to do:

https://i.stack.imgur.com/Xksgx.png

If someone selects the filter options "SDG 2: Zero Hunger", "1: Discussion Project", and "Demographic", the user will click submit and then only the first card that has all those things will show up on the right of it, not the second one underneath it.

I've tried using URLSearchParams but I haven't been able to get it to work. I'm not sure how to go about this problem as the other stackoverflow forums for similar questions use that. This is the react frontend code I have (the only parts that matter are handleSubmit and componentDidUpdate), right now I just want to console.log the object that I got from the database which I filtered:

import React, { useEffect, useState } from 'react'

class Dropdown extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        sdg: 'SDG 1: No Poverty',
        assignment_type: 1,
        theme: 'Demographic'
    };
  
      this.handleSDGChange = this.handleSDGChange.bind(this);
      this.handleAssignmentChange = this.handleAssignmentChange.bind(this);
      this.handleThemeChange = this.handleThemeChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    
    // Handling all 3 input changes
    handleSDGChange(event) {
      this.setState({sdg: event.target.value});
    }

    handleAssignmentChange(event) {
        this.setState({assignment_type: event.target.value});
    }

    handleThemeChange(event) {
        this.setState({theme: event.target.value});
    }

    componentDidUpdate() {
        const fetchProjects = async () => {
            const response = await fetch('/api/projects' + URLSearchParams({ sdg: this.state.sdg})) // Will add other 2 later, testing out 1 first
            const json = await response.json() // contains array of projects

            if (response.ok) {
                console.log(json)
            }
            else {
                console.log(json.error)
            }
        } 

        fetchProjects()
    }

    // Handling all 3 input submissions
    handleSubmit(event) {
        console.log(this.state.sdg)
        alert(this.state.sdg + '--- Assignment Type: ' + this.state.assignment_type + '--- Theme: ' + this.state.theme);
        event.preventDefault();
        
        this.componentDidUpdate()
    }

    
    

    render() {
      return (
        <form onSubmit={this.handleSubmit}>
            <label>SDG:</label>
            <select value={this.state.sdg} onChange={this.handleSDGChange}>
                {/* <option>Select SDG</option> */}
              <option value="SDG 1: No Poverty">SDG 1: No Poverty</option>
              <option value="SDG 2: Zero Hunger">SDG 2: Zero Hunger</option>
              <option value="SDG 3: Good Health & Well Being">SDG 3: Good Health & Well Being</option>
            </select>

            <label>Assignment Type:</label>
            <select value={this.state.assignment_type} onChange={this.handleAssignmentChange}>
              <option value="1">1: Discussion Project</option>
              <option value="2">2: PDF Case study</option>
              <option value="3">3: Community Project</option>
            </select>

            <label>Theme:</label>
            <select value={this.state.theme} onChange={this.handleThemeChange}>
              <option value="Demographic">Demographic</option>
              <option value="Economical">Economical</option>
              <option value="Socio-cultural">Socio-cultural</option>
              <option value="Technological">Technological</option>
              <option value="Ecological">Ecological</option>
              <option value="Poltical">Poltical</option>
            </select>

            <input type="submit" value="Submit" />
        </form>
      );
    }
  }
export default Dropdown

I'm also unsure how I can access this data in my express.js backend, here is what my GET route looks like:

const getProjects = async (req, res) => {
    const projects = await Project.find({}).sort({ createdAt: -1 })

    res.status(200).json(projects)
}

How do I send my parameters for the GET request from my class component to the backend which then can query the MongoDB and get only the filtered objects?

Soccerball123
  • 741
  • 5
  • 17
  • In find you need to pass filter details so that only those documents will be returned which matches every filter. – GodWin1100 Jul 20 '22 at 19:55
  • Yep I realized that, but how do I get my parameters to the backend in the first place so I can pass that in `.find()`? – Soccerball123 Jul 20 '22 at 19:56
  • 1
    you can pass them via query and in server you can get those query in object from [req.query](https://www.geeksforgeeks.org/express-js-req-query-property). [How to pass query param using fetch](https://stackoverflow.com/questions/35038857/setting-query-string-using-fetch-get-request) – GodWin1100 Jul 20 '22 at 20:00
  • I already pasted you a link how to read query params in express in the question you deleted. – Konrad Jul 20 '22 at 21:03
  • What do I specify in the frontend in terms of how to pass the object data? Do I still let the method be `GET` and instead of `body: { ... }` do I do `req: { ... }` or something? – Soccerball123 Jul 21 '22 at 13:07

0 Answers0