I am building a react app with a Firebase backend and I am stuck on fetching data in multiple steps where I use data from the first fetch as a parameter for data from the second fetch.
Below is my code:
// GET DATA FROM FIRESTORE
const { getQrCode, getBranch } = DatabaseService();
This is how I fetch the first data. I have the ID in this case.
// GET QR CODE
const fetchQRCode = async () => {
const data = await getQrCode(id); //I have this ID
setBranchQr(data);
};
This is the second fetch that I need using the data from the first fetch:
// GET BRANCH DATA
const fetchBranchData = async () => {
const data = await getBranch(branchQr.branchId); //I get this from the first fetch
setBranchData(data);
console.log(data)
};
These are the useEffects:
useEffect(() => {
fetchQRCode();
fetchBranchData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {}, [branchQr, branchData]);
2
Answers
Your approach seems to be problem-free. I usually use
react-query
to handle fetch requests because it simplifies the process and makes it straightforward. Withreact-query
, there’s no need to manually use setState or other React hooks like useEffect. Additionally, there’s no need to set isLoading, and it offers a many tools to simplify the work.I would recommend you to take a look at the
Dependent Queries
page ofreact-query
at this link.Here’s a simple example of using
react-query
from the official website:Here is a step-by-step gruid:
index.tsx
orApp.tsx
:Just like said by Pooria, I would use Tanstack Queries
Install it using npm or yarn:
Import it to your root JS file:
Create the client
Wrap your root app
Import your useQuery
Get the first set of data
Create the branch ID from that first set of data
Get the second set of data:
If you logged branches, you should see the data you are looking for.