DannyDevs logopart of logo

lab003: Having fun with a Random Yes/No free API

July 23, 2022


Ask a yes/no question:

hint: questions end with a '?'!

The answer is:


Analysis

This fun little lab hinges on a fun little api at https://yesno.wtf/api, which returns a random ‘yes’ or ‘no’ result.

I adapted it from the Vue docs. It’s used to demonstrate watchers. Below you can see a watch function that observes the ‘question’ reactive variable, and when it observes a change in ‘question’, it runs its anonymous callback function.

In this case, we are checking if the newQuestion includes a ‘?’ in it. If so, we change the answer.value to ‘Thinking…’ as a primitive loading screen.

Finally, we try to fetch an answer from the yesno.wtf api. We then convert that response to JSON, and set our reactive variable answer to the response.answer, which then updates in the template.

The code below is the watch function.

watch(question, async (newQuestion, oldQuestion) => {
  if (newQuestion.includes('?')) {
    answer.value = 'Thinking...'
    try {
      const res = await fetch('https://yesno.wtf/api')
      answer.value = (await res.json()).answer
    }
    catch (error) {
      console.log('Error fetching data: ', error)
    }
  }
})
watch(question, async (newQuestion, oldQuestion) => {
  if (newQuestion.includes('?')) {
    answer.value = 'Thinking...'
    try {
      const res = await fetch('https://yesno.wtf/api')
      answer.value = (await res.json()).answer
    }
    catch (error) {
      console.log('Error fetching data: ', error)
    }
  }
})

End Notes

Interestingly, in addition to ‘watch’ Vue offers ‘watchEffect’. This article advises that we think of watchEffect() as a a variant of computed() that doesn’t return a value but instead triggers side-effects for every reactive variable referenced within its callback function.

Watch(), on the other hand, has you specify which specific reactive variable you want to observe for changes and runs its callback function accordingly.

Watchers of both kinds are useful tools in the Vue toolbox. Make sure you understand their differences in order to deploy them appropriately. DannyDevs out!

Home

Lab

Blog

About

Links