Today we’ll look at how to create a custom hook in Vue.js. For this purpose, we’ll create a simple useFetch hook that we can reuse in our components.
The composition API in Vue 3 appeals to me.
- Especially now with the script setup allowing us to use everything you define, it just makes sense.
- I worked with, and love React, this new development in Vue.js really levels the playing field for me.
- I’d like to walk you through it step by step, so here we go:.
- We start by creating our useFetch function, since it’s a hook we’ll start our function name with ‘use’ as convention dictates.
- Next, we decide the data we want to retrieve when we call our useFetch hook and store it in a state object.
- When we call our function we want to know whether it is loading or not, if it threw an error and if so, we would like to receive the error message.
- Finally, we need the data returned by the call.
- We make our state object reactive because we will change these values while fetching and we want our state to listen to these changes.
Simple POST request with a JSON body using fetch
We could also create single refs for each of our reactive state items but since it all groups nicely together I think a reactive object is more suitable and readable. At the end of our useFetch hook we return our state with the spread operator and the toRefs function.
The toRefs function allows us to destructure our state properties without losing reactivity.
Before we continue let’s properly type our state:. Before we continue we add types to our state. Since the data we’ll return differs per call we use a generic to solve this. Now when we call our useFetch hook we can pass along the return type of our data.
Let’s continue:. Next up we’ll add an async function to be able to fetch our data. The first thing we do is set our isLoading state to true, the process is beginning.
Vue Fetch POST example
Then, in our try block, we set a constant named response and await fetch with a url and (optional) options. Notice that we added the url and options as parameters to the useFetch hook.
We check for response.ok because by default the catch handler is only reached when the fetch fails to make the request. With the response.ok check, we force other errors to also move to the catch handler. If there is no error we fill our state data with the response.json(). If there is an error we set our hasError state to true and add the error message to our errorMessage state. Finally, we set our isLoading state back to false.
Let’s finalize our hook:. The last thing we have to do is call our fetchData function, we await the result so our useFetch function needs to be async.
With this, our useFetch hook is ready to use. You can use our new hook in an (async) function really easily. When you want to fetch and use data directly in your component, there are more implementation options.
This is because the top-level await in the script setup must be used in combination with Suspense, which is still an experimental feature.