Vanilla JS Server Side Rendering

This is a basic function which uses template literals, it can run the functions inside of a string which lets us to do many things like, retrieve data.


This content originally appeared on HackerNoon and was authored by EmreKanbay

\

TL;DR (Too Long Didn't Read)

Function

const render = async (x, ...values) => {
  var rendered = "";
  for (let u = 0; u < x.length; u++) {
    rendered = rendered.concat(x[u]);
    if (u < x.length - 1) {
      if (typeof values[u] == "function") {
        var res = await values[u]()
        if(res) rendered += res;
      } else {
        rendered +=values[u]
            }
    }
  }
  return rendered;
};

Usage

const result = render`My string is = ${()=> {return (1 + 1)}}`

console.log(result)
// output -> My string is 2

What Is This?

By render, I meant being able to run async and sync functions inside of a string. Which may be called templating.

\ This is a basic function which uses template literals, it can run the functions inside of a string which lets us to do many things like, retrieve data from database, fetch data from an API, calculate stuff which is provided earlier and so on.

How it works

You may understand what it does from the code above if you have prerequisite knowledge about tagged templates, it just runs the functions and put the output of function in the place where function executed.

Warning

In many times using async functions inside async functions inside async functions are required and without using proper async await functionality, this stuff is getting too error prone. It may return [Object Promise][Object Promise][Object Promise]. With a simple Promise.all(), we can fix all of that.

\

Promise.all()

\ Examples below.

Rendering list

Just like react, we will use .map() function.

await render`
    Here is my headings:
    ${() => {
      return "".concat(
          ...[1,2,3,4,5].map((t) => {
            return `<h1>My number is: ${t}</h1>`
          }),
      );
    }}
// output: Here is my headings:
// <h1>My number is: 1</h1><h1>My number is: 2</h1><h1>My number is: 3</h1><h1>My number is: 4</h1><h1>My number is: 5</h1>

Examples

Retrieve data from DB

Promise.all() here is not necessary because there is no asynchronous function inside them

await render`
Here is my data
${async () => {
  const text = `SELECT * FROM table`;
  const values = [];
  var record = await pool.query(text, values);
  return "".concat(
    ...(await Promise.all(
      record.rows.map((t) => {
        return `<h1>${t.data}</h1>`
      }),
    )),
  );
}}
`

Fetch data from api

await render`
Here is my data
${async () => {
  const res = fetch("https://example.com", {method:"GET"})
  const data = await res.json()
  return "".concat(
    ...(await Promise.all(
      data.first.map((t) => {
        return `<h1>${t.data}</h1>`
      }),
    )),
  );
}}
`

\


This content originally appeared on HackerNoon and was authored by EmreKanbay


Print Share Comment Cite Upload Translate Updates
APA

EmreKanbay | Sciencx (2024-10-02T15:26:30+00:00) Vanilla JS Server Side Rendering. Retrieved from https://www.scien.cx/2024/10/02/vanilla-js-server-side-rendering/

MLA
" » Vanilla JS Server Side Rendering." EmreKanbay | Sciencx - Wednesday October 2, 2024, https://www.scien.cx/2024/10/02/vanilla-js-server-side-rendering/
HARVARD
EmreKanbay | Sciencx Wednesday October 2, 2024 » Vanilla JS Server Side Rendering., viewed ,<https://www.scien.cx/2024/10/02/vanilla-js-server-side-rendering/>
VANCOUVER
EmreKanbay | Sciencx - » Vanilla JS Server Side Rendering. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/10/02/vanilla-js-server-side-rendering/
CHICAGO
" » Vanilla JS Server Side Rendering." EmreKanbay | Sciencx - Accessed . https://www.scien.cx/2024/10/02/vanilla-js-server-side-rendering/
IEEE
" » Vanilla JS Server Side Rendering." EmreKanbay | Sciencx [Online]. Available: https://www.scien.cx/2024/10/02/vanilla-js-server-side-rendering/. [Accessed: ]
rf:citation
» Vanilla JS Server Side Rendering | EmreKanbay | Sciencx | https://www.scien.cx/2024/10/02/vanilla-js-server-side-rendering/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.