September 11, 2020

Building Your Own Hook for fetching data from database.

A custom Hook is a JavaScript function whose name starts with ”use” and let you use state and other React features without writing a class.

Domantas Jovaisas profile on CodeMash

Domantas Jovaišas

Founder of CodeMash

When you build data-driven applications a lot you may catch your self by doing a lot of repeatable and tedious work. Some developers tend to have an application logic separated into separate files and do fetching data calls from there. For more sophisticated scenarios they use Redux, Saga, and Context techniques. This may be a good reason to do so, but in more cases when we are talking about just how to fetch the data and represent it into our application we use simple hooks like use-http.  

use-http is a package that provides hooks for fetching data. Instead of using await fetch() and handling loading, error, and success states yourself, useFetch() allows you to access these states in just one line of code. 

Nevertheless, we’ve put more synthetic sugar when we are talking about work with API.  In this example, we will show you how to create a custom hook, that fetches data from the database and outputs various parameters like isLoading, isRefreshing, noMoreData, totalAmount of records, and result.

This custom hook is useful when you want to have a reusable component. As a result, it gives you less code to write and that means your code is less error-prone.  Also, it gives you the capability to work hand in hand with a component like list. So when you pass parameters from your list, it automatically works with hook and passes data back and forth. As an example, you can check out our blog post to get more feeling of how it works with the custom list in React Native project.

Custom Hook that fetches data

This custom hook waits for parameters like collectionName, filter, pageSize, pageNumber, sort, projection, referencedFields. Behind the scenes, it calls CodeMash using standard fetch API.  

When something bad happens as a result indicator isLoading is set to false and the error message is saved to errorMessage property for later use. Otherwise, there is some logic that basically tries to save response to result property. On top of that, we return the total amount of records and if there is a need to call API again. This is very useful when you have a list in react native application and when you scrolling down you want to get more data. Knowing how much do you have total records in database and how much you fetched in your list, you can prevent extra roundtrips to your server.

All code you can find in our GitHub repository. Please go ahead and try it, and of course, let us know if it’s useful.