Home > Blockchain >  Stimulus build html element from rest API
Stimulus build html element from rest API

Time:10-25

Hello I have a stimulus code into my symfony project. This code is calling a rest API which taking around 3 seconds to provide the response. This rest api return JSON.

This is my code :

import {Controller} from "@hotwired/stimulus";
import axios from "axios";


export default class extends Controller {
    static values = {
        url: String
    }

    connect() {
        axios.get(this.urlValue)
            .then((r) => {
                if (r.data !== null) {
                    let html
                    const tmp = JSON.parse(r.data)
                    if (tmp === null) {
                        html = document.createElement("div")
                        html.classList.add("alert", "alert-danger", "alert-dismissible", "fade", "show")
                        html.innerHTML  = "Asset Number Not Valid";
                        html.innerHTML  = "<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"alert\" aria-label=\"Close\"></button>"
                    } else {
                        html = document.createElement("ul")
                        html.classList.add("list-group")
                        for(let key in tmp) {
                            html.innerHTML  = "<li class=\"list-group-item\">"   key   " : "   tmp[key]   "</li>";
                        }
                        html.innerHTML  = "</ul>";
                    }
                    this.element.replaceWith(html);
                }
            })
    }
}

As you can see, it's building a list or display an error. This code is really simple and works well. I just don't like how html is build.

Do you have any other/cleaner way ?

CodePudding user response:

You can create HTML in separated functions below connect method, for example:

errorMessage() {
  const div = document.createElement("div");
  div.innerHTML = `
    <p>Some HTML here</p>
    ... More html

  `

  return div;
}

Then in response you just call:

this.errorMessage();

The same goes for successful response. So in the end in your response you can either have this.errorMessage() or this.appendList() or whatever you gonna call your function.

  • Related