how to display in react JavaScript a recursive data from MySQL

22 Views Asked by At

thanks in advance.

so i have a blog(react, JavaScript, python, MySQL) and i want to add comments system that support nested comments.

so far that's what i have(after reading and searching for similar cases in stack overflow):

my comments table look like that:

comment_id, article_id, comment_parent_id, message, user_id,

my recursive query look like that:

(this query will fetch all comments for a specific article id)

WITH RECURSIVE CommentHierarchy AS (
  SELECT comment_id, comment_parent_id, message, user_id
  FROM comments
  WHERE article_id = 11 AND comment_parent_id IS NULL
  UNION ALL
  SELECT c.comment_id, c.comment_parent_id, c.message, c.user_id
  FROM comments c
  INNER JOIN CommentHierarchy ch ON c.comment_parent_id = ch.comment_id
  )

SELECT * FROM CommentHierarchy

the out put of this query look like this:

[
  {'comment_id': 7, 'comment_parent_id': None, 'message': '"very cool article thanks"', 'user_id': 18}, 
  {'comment_id': 13, 'comment_parent_id': None, 'message': '"ohh good to know"', 'user_id': 12}, 
  {'comment_id': 8, 'comment_parent_id': 7, 'message': '"yea i enjoy that one too"', 'user_id': 14}, 
  {'comment_id': 9, 'comment_parent_id': 7, 'message': '"hope there will be more like this one"', 'user_id': 12}, 
  {'comment_id': 14, 'comment_parent_id': 13, 'message': '"yea i didnt know ether"', 'user_id': 14}, 
  {'comment_id': 15, 'comment_parent_id': 14, 'message': '"glad i got to read this"', 'user_id': 17}
]

its a list of the comments that the parents(top lvl) are first in the list and then the children..

i dont know how to present that results in react. so far i did something like that:

{articleComments.map((comm)=> {
  if(comm['comment_parent_id'] == null){
    return <>
      <div key={comm['comment_id']}>{comm['message']}</div>
      {articleComments.map((rep)=>{
        if(rep['comment_parent_id'] == comm['comment_id']){
          return <>
            <div key={rep['comment_id']}>{rep['message']}</div>
            {articleComments.map((subrep)=>{
              if(subrep['comment_parent_id'] == rep['comment_id']){
                return <>
                  <div key={subrep['comment_id']}>{subrep['message']}</div>
                </>;
              }
            })}
          </>;
        }
      })}
    </>;
  }
}

which is very messy and wrong also limit my nested depth/lvl..

so i belive i might have problem with my recursive query that give me the results not arranged good, maybe it should be a list of parents(top lvl) and inside each parents a list of his children and inside each children a list of his children if there is... and so on. but i dont know how the query should be to get results like that and if its the right way, maybe my current query is good enough and i just need to know how to display it in react correctly.

Thank you all

0

There are 0 best solutions below