I'm clicking a button to make a call to an API to get a random fact and length. This is then displayed in two input fields which works. I'm struggling with how to change the text in the input fields to the new fact and length from the API when the button is clicked again. I know it is something simple but can't seem to find the solution. Any help would be appreciated.
<template>
<form>
<header>
<img alt="Vue logo" src="./assets/logo.svg" width="300" height="300" />
<br>
<br>
<input type="text" id="idFact" v-model="facts">
<br>
<br>
<input type="text" id="idLength" v-model="lengths">
<br>
<br>
<button v-on:click="callAPI" type="button">Call</button>
</header>
</form>
</template>
<script>
export default {
data() {
return {
posts: '',
facts: '{fact}',
lengths: '{length}',
};
},
methods: {
async getData() {
try {
let response = await fetch("https://catfact.ninja/fact");
this.posts = await response.json();;
} catch (error) {
console.log(error);
}
},
callAPI() {
this.facts = this.posts.fact
this.lengths = this.posts.length
}
},
created() {
this.getData();
}
}
</script>
Thanks
CodePudding user response:
Invoke the getData
method inside the click handler callAPI
, and remove the call from created
hook in order to avoid redundant calls:
<script>
export default {
data() {
return {
posts: '',
facts: '{fact}',
lengths: '{length}',
};
},
methods: {
async getData() {
try {
let response = await fetch("https://catfact.ninja/fact");
this.posts = await response.json();;
} catch (error) {
console.log(error);
}
},
callAPI() {
this.getData()
this.facts = this.posts.fact
this.lengths = this.posts.length
}
},
}
</script>