1
I’m trying to understand how Xios works, but I’m stuck when it comes to printing the information on the screen. I can view the result through the browser console and a Undefined on top, but I don’t think there’s any way to solve.
Another problem is that instead of the result, the code shows all the content of the function as text. Where I am missing?
function titulo() {
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(res => {
console.log(res.data.title);
});
}
titulo();
function myFunction() {
document.getElementById("demo").innerHTML = 'Título do post: ' + titulo; //o que inserir aqui para que seja mostrado o title vindo do axios?
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.js"></script>
<p id="demo" onclick="myFunction()">Clicar para mudar o texto.</p>
The problem is that the request is done asynchronously, hence the code that displays the text is executed before the request is processed, you would have to perform the command inside the
then
or useasync
await
– Denis Rudnei de Souza