Questions when returning data from an API to html?

Asked

Viewed 219 times

-2

The problem is that by clicking the convert button it consumes the API E shows the correct quote in the debug and console. But in time to pass the value moedaBVal = cotaçao * moedaAVal he passes as moedaBVal = undefined or NaN. What could be the problem here? Follows the code:

        class Converter {
            converter() {
                let moedaA = "USD";
                let moedaB = "BRL";
                /* let moedaBVal = 0; */
                let moedaAVal = document.getElementById("inputUSDBRL").value;
                let de_para = moedaA + "_" + moedaB;
                let url = `https://free.currconv.com/api/v7/convert?q=${de_para}&compact=ultra&apiKey=234428564665e4c14ce2`;
                fetch(url).then(res=>{return res.json()}).then(json=>{
                    let cotacao = json;
                    let moedaBVal = cotacao * moedaAVal;
                    

                });
                
                
            }
        }
        class Controller {
            constructor() {
                this.converter = new Converter();
            }
            aoClicarConverter() {
                let converter = this.converter.converter();


                let div = `<h5>${converter}</h5>`;

                document.getElementById("resultadoUSDBRL").innerHTML = div;
            }
            domInputDolarEmReais() {
                let moedaA = "USD"
                let moedaB = "BRL"
                let div = document.getElementById("titlleConversorUSDBRL")
                div.innerHTML = moedaA + " Para " + moedaB


            }
        }
        let controller = new Controller;
<body onload="controller.domInputDolarEmReais()">
    <h5 id="titlleConversorUSDBRL"></h5>
    <input type="number" placeholder="USD" id="inputUSDBRL">
    <button onclick="controller.aoClicarConverter()">Converter</button>
    <div id="resultadoUSDBRL"></div>
</body>

   
    

    

  • You will need to handle the api call. In function. With async, and promisse. I will see if I can get example and post.

  • If possible, change the question title to something more descriptive, remember when you Google search and find titles that are "exactly what you need". Try to provide the same feeling when someone finds your question too :)

2 answers

0

From what I saw of your code, there are 2 problems, the first is that to read the return of the quotation (in the json variable), you need to do "quotation.USD_BRL" to access the result.

The second is that the code is asynchronous, when you call this.converter.converter()" it will not wait for the return, so it will not appear the result on the screen even as this setting.

To work, the functions "aoClicarConverter" and "convert" would have to have the following adjustments:

<script>
    class Converter {
        converter() {
            let moedaA = "USD";
            let moedaB = "BRL";
            /* let moedaBVal = 0; */
            let moedaAVal = document.getElementById("inputUSDBRL").value;
            let de_para = moedaA + "_" + moedaB;
            let url = `https://free.currconv.com/api/v7/convert?q=${de_para}&compact=ultra&apiKey=234428564665e4c14ce2`;
            fetch(url).then(res=>{return res.json()}).then(json=>{
                let cotacao = json;
                
                let moedaBVal = cotacao.USD_BRL * moedaAVal;
                let div = '<h5>' + moedaBVal + '</h5>';
                document.getElementById("resultadoUSDBRL").innerHTML = div;

            });
            
            
        }
    }
    class Controller {
        constructor() {
            this.converter = new Converter();
        }
        aoClicarConverter() {
            let converter = this.converter.converter();

        }
        domInputDolarEmReais() {
            let moedaA = "USD"
            let moedaB = "BRL"
            let div = document.getElementById("titlleConversorUSDBRL")
            div.innerHTML = moedaA + " Para " + moedaB


        }
    }
    let controller = new Controller;

</script>

0

Come on, to keep the default code, you should use async and Promise for the call that shows the result in html, "wait" the api work first and only after having the result it present on the screen.

class Converter {
    converter() {
        let moedaA = "USD";
        let moedaB = "BRL";
        let moedaAVal = document.getElementById("inputUSDBRL").value;
        let moedaBVal = 0;
        let de_para = moedaA + "_" + moedaB;
        let url = `https://free.currconv.com/api/v7/convert?q=${de_para}&compact=ultra&apiKey=234428564665e4c14ce2`;
        return new Promise((resolve, reject) => {
            fetch(url)
            .then(res=>{
                return res.json();
            })
            .then(json=>{
                resolve(
                    (parseFloat(moedaAVal) * json[de_para]).toFixed(2)
                    );
            })
            .catch(err => {
                reject(err);
            })
        })
    }
}
class Controller {
    constructor() {
        this.converter = new Converter();
    }
    async aoClicarConverter() {
        let converter = await this.converter.converter();
        document.getElementById("resultadoUSDBRL").innerHTML = converter;
    }
    domInputDolarEmReais() {
        let moedaA = "USD"
        let moedaB = "BRL"
        let div = document.getElementById("titlleConversorUSDBRL")
        div.innerHTML = moedaA + " Para " + moedaB


    }
}
let controller = new Controller;
<!DOCTYPE html>

<html>
    <head>
        <script defer src="./index.js"></script>
    </head>
    <body onload="controller.domInputDolarEmReais()">
        <h5 id="titlleConversorUSDBRL"></h5>
        <input type="number" placeholder="USD" id="inputUSDBRL">
        <button onclick="controller.aoClicarConverter()">Converter</button>
        <div id="resultadoUSDBRL"></div>
    </body>
</html>

Explaining the code:

In this passage:

 return new Promise((resolve, reject) => {  // é utilizado um promise, onde o resolve espera o cálculo ser feito, para assim retornar o return res.json();
        fetch(url)
        .then(res=>{
            return res.json();
        })
        .then(json=>{
            resolve(
                (parseFloat(moedaAVal) * json[de_para]).toFixed(2)
                );
        })
        .catch(err => { // no caso de erro, ele retornao erro.
            reject(err);
        })


async aoClicarConverter() { // aqui utiliza-se um async, onde só irá preencher o converter após a api retornar ok. (resolve do promise).
            let converter = await this.converter.converter();

Study more about these commands, hint: https://www.youtube.com/watch?v=nRJhc6vXyK4 https://www.youtube.com/watch?v=h0sNAXE1ozo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.