Good evening, I have a button with an onclick event that starts ObjectCard () when clicked where the result is an object that changes based on the input in the x text box. Except that at the first click it always returns undefined or the previous result (the old value of x). Could you help me and explain why? Thank you!
let carta = "";
function ObjectCard(){
let x = document.getElementById("searchtext").value;
const url = "https://api.scryfall.com/cards/named?fuzzy=";
return fetch( url + x)
.then(response => {
return response.json();
})
.then(response => carta = response)
.then (console.log(carta))
};
This is the button with onclick event
<button className="btn inline-block px-6 py-2.5 bg-blue-600 text-white font-medium text-xs leading-tight uppercase rounded-r-lg shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out flex items-center transition-all ease-in-out hover:-translate-y hover:scale-125 hover:rounded duration-300" type="button" id="button-addon2" onClick={ObjectCard}>
<Link to="/searchpage"><svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="search" className="w-4" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path fill="currentColor" d="M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"></path>
</svg></Link>
</button>
I think that in this occasion you should use async/await statement, like for example:
let carta = "";
async function ObjectCard(){
const inputValue = document.getElementById("searchtext").value; // Renamed "x"
const url = "https://api.scryfall.com/cards/named?fuzzy=";
const response = await fetch( url + inputValue ); // Response from fetch without parsing to json
const parsedResponse = await response.json(); // Parsing response
carta = parsedResponse
return parsedResponse;
}
Nevertheless i recommend you to abstract your service methods, and do it this way:
let carta = "";
const inputValue = document.getElementById("searchtext").value; // Renamed "x"
async function getCard(searchedCard){
const url = "https://api.scryfall.com/cards/named?fuzzy=" + searchedCard;
const response = await fetch(url); // Response from fetch without parsing to json
const parsedResponse = await response.json(); // Parsing response
return parsedResponse;
}
getCard(inputValue).then(res => carta = res);