skip to Main Content

I have a fully functional social media app and an API made with Express, Pug and JavaScript which is server-side rendered.

For example, when I comment on a post the comment is added but I have to manually reload the page for it to be displayed.

I’m wondering if there is a way to display and update the content without the need to reload the page using JS?

Or should I just make the app client-side rendered with react?

This is the link for the app https://github.com/Fedechini/kleory

2

Answers


  1. Yes, you have to make the app client-side rendered. In template engine you cant use react hooks, I mean you have to use useState, useEffect to load comments without loading the page.

    Login or Signup to reply.
  2. If you do not want a page refresh, you have to use Ajax to submit the new comment, and to display the new comment in the page you need to use dynamic Html with client side scription.

    It should be something like the following which doesn’t work in JSFiddle:

    const submit = () => {
      const data = { comment: document.getElementById("text").value };
      fetch("/123/comments", { method: "POST", 
         body: JSON.stringify(data),
         headers: { "content-type": "application/json"}}
      ).then(resp => resp.json().
         then(comment => {
           document.getElementById("comment").innerText = comment; }).
         catch(err => {
           console.log("error");
         }
      ).catch(err => {
          console.log(err);
        })
      );
    }
    <label>Comment:
     <textarea id="text"></textarea>
     </label>
     <button onclick="submit();">Submit</button>
     <p>Comment:
       <span id="comment"></span>
     </p>

    A summary of the steps when user clicks the Submit button:

    1. Extract the value of the next comment from the <textarea>.
    2. Invoke a fetch (only in new browsers) call to perform an asynchronous Http POST request to send the new comment to your backend to insert into your database.
    3. Your /:postId/comments function should return a Json response with the new comment is successfully inserted.
    4. The fetch callback receives the newly inserted comment from the backend and displays it in the <span> element.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search