Prerequisite: Basic familiarity with Firebase concepts like collections, documents, and queries
In this two part series, you will learn how to implement RTK query in a React Native project backed by Firebase. Part one will teach you how to build an API layer when building mobile/web apps and why you need one. In part two of this series, you will learn how to implement an API layer with RTK query. Both parts will focus on retrieving data from firestore, rather than altering it.
If you want to follow along in your own sandbox, import the @reduxjs/toolkit package. You’ll also need a Firebase backend connected. If you’re not familiar with setting up a Firebase project with React Native, you can check out a previous article I wrote here. Or watch this video starting around the 5 minute mark.
Why you should create an API layer
A very common practice in React is to use an useEffect hook to make API calls in a React component as demonstrated below.
While this approach can work well with smaller applications, it will start to become a headache if you try to scale it across multiple components. What if you’re lead engineer decides to use Axios instead of fetch? You would need to update many components to accommodate such a decision. Such an event, would expose your design decision as being complex.
In his e-book, ”A philosophy of Software design”, John Ousterhout states change amplification as a symptom of complexity.
The first symptom of complexity is that a seemingly simple change requires code modifications in many different places.
When you couple API calls to React components, you increase complexity within your code base as it grows because a simple change will require modifications in many different places. So how can you make your code less complex?
In his book, “React, The Road To Enterprise”, Thomas Findlay encourages developers to separate their API code from the rest of their code for the following benefits:
Adaptability
I will demonstrate how to create an API layer with Firebase. But what if you’re in a situation where the team lead decides to transition from Firebase to Supabase? Or what if your team hires a .NET developer and decides to build a custom made API? If you’ve created an API layer, it will be easier to adapt to these changes.
standardisation
When you create a separate API layer, you can avoid the temptation to use fetch in one part of your app and Axios in another. In other words, an API layer creates a path that future developers or you future self wont have to guess about.
Firebase API layer
Lets break this code down. The first thing to notice is the file path. By creating an API directory and placing all of our code that hits “endpoints” on our backend, we create a layer between React Native and our backend.
Another point to notice is the menuItemsApi file holds code related to all menuItem features. Right now it only holds code to getMenuItems but in the future if I wanted a feature that allowed a user to add menu items, I would put it in the menuItemsApi file.
Finally, if I decided to go with Database functions from Supabase, I would replace my code in this directory instead of trying to update multiple parts of my app.
If you’re familiar with Firebase V9, you can skip the following section. If not, continue reading to understand the rest of the code in menuItemsApi.
Firebase V9 methods
query - The query method, as the name suggest, is meant to query our database according to parameters a developer will set. Right now its querying my menu items collection according to the genre field. It will also limit my request to 3 documents per request.
menuItemsRef - This variable represents the collection or data I want to query. Behind the scenes it looks like this:
const menuItemsRef = collection(db, "Menu Items");
The code above is telling firebase to allow us access to the Menu Items collection in our database
orderBy - The orderBy method is responsible for how our returned documents will be sorted. By placing “genre” as an argument to the orderBy method, I’m telling Firebase to send me menu items in alphabetical order according to their genre. For example, my current database has menu items with the following genre: Burgers, BBQ, and Asian Food. With my current query and orderBy method, Firebase would return my documents in this order: Asian Food, BBQ, Burgers
limit - This method is responsible for limiting the amount of documents a query will return. My current example will return 3 documents at a time.
getDocs - Opposite of getDoc which returns a single document, getDocs returns multiple documents and is appropriate when making queries without knowing the results in advance.
lastDocument - This variable is holding the last item’s genre from the results of getDocs. This is the beginning of the process for creating pagination with cursors. Pagination is beyond the scope of this article.
payload - This variable will receive the results from our getDocs request and with lastDocument will be given to RTK query to manage our request and server state. This will be demonstrated in part two of this series.
Updated useEffect example
If we revisit our previous useEffect example, we will see our code is more Orthogonal or decoupled.
Now if we decided to use Axios, Supabase, or something other database technology, we would only need to change the code in our API directory and not throughout the whole app. In part two, you will learn how to implement our API ayer in RTK query where you will gain the benefits of caching and network state management.
Ways to support my newsletter
🖥 If you believe this content is valuable, share it on social media
🎤 If you believe I would be a good fit for a podcast, let your favorite podcaster know
Connect with me
Connect with me on LinkedIn!
Connect with me on Twitter!
Related Articles:
React vs React Native Pt1
Image by RealToughCandy.com A common question I get from experienced React developers interested in React Native is, what are some of the differences between React and React Native. I will explain some core differences in today’s article. This will not be an exhaustive list but it will be a great starting point for those interested in learning about Reac…