Arquisoft / radarin_en2b

0 stars 2 forks source link

List nearby friends of current user #89

Closed UO271405 closed 3 years ago

UO271405 commented 3 years ago

I am having some trouble when trying to put in an array the friends of the current user in order to pass them to the database and get the nearby friends. I know how to directly put them inside a List element but not inside the array. Any idea?

UO271405 commented 3 years ago

Good afternoon @pglez82,

I have a problem regarding listing the nearby friends of the user. I put you in context:

I am using react hooks to return a list of nearby friends and a list of all friends of the current user. The second one (the list of all friends) is already processed and shown in the react return statement.

The problem comes when trying to list the nearby friends. In order to do that, I have to call the mongodb database to get the nearby friends of the current user and create a list dynamically depending on the number of friends I have received. This can not be done in the react return statement so I do it in the react effect hook (useEffect). The problem comes when trying to create the list of nearby friends dynamically. I use the method document.createElement("element") to create all the elements I need and finally use the method appendChild(element) to add the element to the DOM. Everything works fine, but the creation of all these elements of the list is performed twice so I always have my list of nearby friends repeated. I tried to remove the inside index.js but it still does not work.

Is there any suggestion on how to do it? Thank you.

pglez82 commented 3 years ago

Usually what you do is call the api method in the useEffect hook and store the result (an array) in the state. Then, in the react return statement just use the function map (https://reactjs.org/docs/lists-and-keys.html) to iterate over the array and print the html element that you want fir each element (a <li> for instance).

Let me know if that helps.

UO271405 commented 3 years ago

Hi @pglez82,

I have tried to do what you said and because of an inifinite loop in useEffect I found out doing research that you can add an array of dependencies on the second parameter of the useEffect. If one of those dependencies is not the same as the one previously used, useEffect is triggered. I also discovered that if you only want useEffect to be executed on the first render, you can pass an empty array on the second parameter. I did that and now the list of nearby friends is not repeated.

It is not really what you told me but it helped me reaching a solution. Thank you!