DEV Community

Nicholas Mendez
Nicholas Mendez

Posted on • Updated on

Understanding Rendering in Web Apps: CSR

Client-Side Rendering

This category includes approaches that make network calls for data and construct HTML all in the browser (AJAX). This is typically done in Single Page Applications (SPA).

Vanilla AJAX

Asynchronous Javascript and XML (AJAX) is a web programming technique whereby the DOM is modified to present data from a network request issued by javascript without refreshing the page.
The following code snippet is an example of such.

<div id="myDiv"></div>

<script>
   //async function to use await syntax on promises
   async function getAndDisplayUser(){
      const div = document.querySelector('#myDiv');
      const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
      const user = await response.json();
      div.innherHTML = `<p> name: ${user.name} phone: ${user.phone} </p>`;//data from URL is 'rendered' to the page using JS
   }

   getAndDisplayUser();
</script>

Enter fullscreen mode Exit fullscreen mode

AJAX in Client-Side Frameworks

Client-side frameworks typically support performing network requests whether by APIs provided by the framework, utilizing other libraries or by using the standard fetch function. Combining that with the framework's templating syntax would allow you to perform AJAX.

Examples

The following is an example of AJAX (CSR) using react axios

// Post a request for a user with a given ID
render() {
  return (
    <div>
      <Get url="/api/user" params={{id: "12345"}}>
        {(error, response, isLoading, makeRequest, axios) => {
          if(error) {
            return (<div>Something bad happened: {error.message} <button onClick={() => makeRequest({ params: { reload: true } })}>Retry</button></div>)
          }
          else if(isLoading) {
            return (<div>Loading...</div>)
          }
          else if(response !== null) {
            return (<div>{response.data.message} <button onClick={() => makeRequest({ params: { refresh: true } })}>Refresh</button></div>)
          }
          return (<div>Default message before request is made.</div>)
        }}
      </Get>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

From my research, it appears that AJAX is the only way to do Client Side Rendering so you may see these terms be used interchangeably.

In the next post, we shall take a look at how these approaches play with the Single Page-Application, Multi-Page Application architectures.

Top comments (0)