Nuxt 3 + useFetch = Reactive Vue at its best 🔥
After primarily using React for frontend development for the past few years, I wanted to see what the competition is doing. Before getting completely lost in React, I used to develop some smaller frontends with Vue 2 and therefore it was my first choice for exploring how it has changed since then. In addition to Vue 3, I also wanted to try Nuxt 3, as it is a popular framework for building web applications with Vue.
After setting up a project with these technologies, two features really caught my eye. Namely, the composition API, which is a fundamental change to how Vue components are structured, and the useFetch composable provided by Nuxt, which allows us to reactively fetch data. And this combination is exactly what this post is about. Let’s have a look on how to utilize these two features to get the best out of Vue’s reactivity.
How to fetch data without useFetch?
Before explaining what useFetch
is and how it works, I want to show you how to fetch data without it. In the example component below we want to be able to iterate over all the Pokémon, which are fetched individually whenever we click on the "next" or "previous" button. For that, we maintain a reactive state called currentId
in this example. Once we want to fetch the next/previous Pokémon, we increase/decrease the value of this state and trigger a fetch from the URL containing the updated ID in the respective functions nextPokemon
and previousPokemon
. We await the response and store the name and the image URL as a second reactive state. When this state changes Vue re-renders the UI and we see the new Pokémon in our web app. Additionally, we need to execute fetching on the initial mount of the component.
This method works perfectly fine, but leaves a stale aftertaste. Fetching, in this case, is implemented in an imperative way, meaning, we tell our program what it needs to do step by step. We’re thus not leveraging Vue’s reactivity to its full extent.
Ideally, we just update one state and all subsequent computations and executions react to this change without us needing to trigger them manually.
How useFetch can improve our component
First we need to understand what the useFetch
method is and how it works. useFetch
is a composable provided by Nuxt.
In the context of Vue applications, a “composable” is a function that leverages Vue’s Composition API to encapsulate and reuse stateful logic.
So, by internally maintaining reactive state and watching for changes of properties provided to it, useFetch
integrates itself seamlessly into the lifecycle of a Vue component it is used in.
useFetch
can be called with a configuration for a http request like the URL, query parameters, headers, body, method, etc. All these properties can either be regular variables or reactive variables (ref
, reactive
, computed
, ...). If a property is reactive and gets updated, useFetch
reacts to this change by executing the request again. The return value of useFetch
is an object containing data
(body of the response), pending
(a boolean indicating if a request is in progress) and error
(object containing information regarding the request error). We will also use the configuration option pick
which allows us to specify which keys of the response data we want to pick and therefore to omit all other keys. More information on the configuration options of useFetch
can be found in the Nuxt docs.
Now let’s refactor our component by making use of useFetch
Instead of executing the fetch function manually whenever we want to see the next/previous Pokémon, we just update the currentId
state. Next we need to make the URL a reactive state by using the computed
function. computed
creates a new reactive variable and updates it whenever a reactive variable it depends on changes. You can find the docs on computed
here.
This concept is called derived state and is explained in detail in this blog post by my dear colleague Johannes Preis.
The last thing left is to provide this URL to useFetch
and adding the pick
configuration option, as mentioned before. We also got rid of the onBeforeMount
hook, as useFetch
performs the request on mount automatically.
That’s it. The only manual change we need to perform is updating the currentId
state. Everything else is fully reactive and gets recalculated/executed automatically.
Passion, friendship, honesty, curiosity. If this appeals to you, Comsysto may well be your future. Apply now to join us!
This blogpost is published by Comsysto Reply GmbH