kubowania / tinder-clone

A Tinder Clone for educational purposes
105 stars 52 forks source link

The gender interest "everyone" is not working #1

Open youngjun827 opened 2 years ago

youngjun827 commented 2 years ago

The gender interest "everyone" does not show any match. Would you happen to know how to fix the issue?

AdaCra commented 1 year ago

I kinda figured it out by changing the index.js - app.get function for "Get all gendered users"

// Get all genderedUsers
app.get('/gendered-users', async (req, res) => {

    const client = new MongoClient(uri)
    let gender
    const everyone = {$exists: true}
    if (req.query.gender === "everyone") {
        gender =  everyone
    } else {gender = { $eq : req.query.gender}}

    try {
        await client.connect()
        const database = client.db('app-data')
        const users = database.collection('users')
        const query = { gender_identity: gender}
        const foundUsers = await users.find(query).toArray()

        res.send(foundUsers)
    } finally {
        await client.close()
    }
})

I converted const gender to let gender and then created the variable const everyone = {$exists: true} which will return all documents with a value in that specific key.

The if statement states that, should thereq.query.gender === "everyone" then let the query return all documents else query for whatever req.query.gender is.

The only issues I then get are due to the useEffect function burning a hole through mongoDB refreshing the query every 100 ms or something stupid. xhr.js:247 GET http://localhost:8000/gendered-users?gender=everyone net::ERR_INSUFFICIENT_RESOURCES

and an Axios error in the user gender interest function. Dashboard.js:35 - AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}

In hindsight, I could probably have changed that query from the app.get user.gender_interest

CaiqueCoelho commented 1 year ago

@AdaCra the burning requests is because the useEffect is running all the time without control of when running, with the last version of react the useEffect hook was changed to re-run multiple times in the life cycle of the component in the screen, to fix that you should control your useEffect to run just when the user is changed and use an useRef to control the component life cycle, something like this will fix your error:

const shouldFetchUser = useRef(true);
  useEffect(() => {
    if (shouldFetchUser.current) {
      shouldFetchUser.current = false;
      getUser();
    }
  }, []);

  const shouldFetchGenderedUsers = useRef(true);
  useEffect(() => {
    if (user && user.user_id && shouldFetchGenderedUsers) {
      shouldFetchGenderedUsers.current = false;
      getGenderedUsers();
    }
  }, [user]);