I'm practicing using fetch with async and await in React, consulting a public API of Rick and morty, but when showing the values it shows them to me 2 times by console (In the view I still don't show anything)
import React from 'react'
const ApiRickAndMorty = () => {
const llamar = async () => {
const url = "https://rickandmortyapi.com/api";
const resp = await fetch(url);
const data = await resp.json();
console.log(data);
}
llamar()
return (
<div>
<h1>Api Rick and Morty</h1>
</div>
)
}
export default ApiRickAndMorty
I tried to change the response of the function to a return and use a console.log directly from the function call, but now it shows me in the console a: Promise pending
import React from 'react'
const ApiRickAndMorty = () => {
const llamar = async () => {
const url = "https://rickandmortyapi.com/api";
const resp = await fetch(url);
const data = await resp.json();
return data
}
console.log(llamar());
return (
<div>
<h1>Api Rick and Morty</h1>
</div>
)
}
export default ApiRickAndMorty
This happens because the function
llamar()
is asynchronous and, when you update the value of the query, it is executed again, that is why you get two results. The easiest solution is to add an await in front of the function call.