skip to Main Content

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


  1. 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. With react-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 of react-query at this link.

    Here’s a simple example of using react-query from the official website:

    // Get the user
    const { data: user } = useQuery({
      queryKey: ['user', email],
      queryFn: getUserByEmail,
    })
    
    const userId = user?.id
    
    // Then get the user's projects
    const {
      status,
      fetchStatus,
      data: projects,
    } = useQuery({
      queryKey: ['projects', userId],
      queryFn: getProjectsByUser,
      // The query will not execute until the userId exists
      enabled: !!userId,
    })
    

    Here is a step-by-step gruid:

    1. Install Tanstack Queries using npm or yarn:
    npm i @tanstack/react-query
    yarn add @tanstack/react-query 
    
    1. Add it into your root js/ts react file like index.tsx or App.tsx:
    import ReactDOM from "react-dom";
    import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
    import App from "src/App";
    
    const queryClient = new QueryClient({});
    
    ReactDOM.render(
      <QueryClientProvider client={queryClient}>
        <App />
      </QueryClientProvider>,
      document.getElementById("root")
    );
    
    
    1. In the component where you want the calls to be made, call the queries as follows:
    import { useQuery } from "@tanstack/react-query";
    
    
    // It's better to use a const for queryKey in order to export and use in future as follows.
    export const REACT_QUERY_GET_QR_CODE_KEY = "GET_QR_CODE_KEY";
    export const REACT_QUERY_GET_BRANCH_QUERY_KEY = "GET_BRANCH_QUERY_KEY";
    
    
    const { data: nameThatMakesSenseToYou } = useQuery({
        queryFn: () =>  getQrCode(id),
        queryKey: [REACT_QUERY_GET_QR_CODE_KEY],
    });
    
    const branchId = nameThatMakesSenseToYou?.branchId;
    
    const { status, data: branches } = useQuery({
      queryKey: [REACT_QUERY_GET_BRANCH_QUERY_KEY, branchId],
      queryFn: () => getBranch(branchId),
      enabled: !!branchId,
    });
    
    
    Login or Signup to reply.
  2. Just like said by Pooria, I would use Tanstack Queries

    Install it using npm or yarn:

    npm i @tanstack/react-query
    

    Import it to your root JS file:

    import { QueryClientProvider, QueryClient } from "@tanstack/react-query";
    

    Create the client

      const queryClient = new QueryClient();
    

    Wrap your root app

        <QueryClientProvider client={queryClient}>
    
        </QueryClientProvider>
    

    Import your useQuery

    import { useQuery } from "@tanstack/react-query";
    

    Get the first set of data

          const { data: nameThatMakesSenseToYou } = useQuery({
        queryFn: () =>  getQrCode(id),
        queryKey: ["qrcode"],
      });
    

    Create the branch ID from that first set of data

      const branchId = nameThatMakesSenseToYou.branchId;
    

    Get the second set of data:

      const { status, data: branches } = useQuery({
        queryKey: ["branch", branchId],
        queryFn: () => getBranch(branchId),
        enabled: !!branchId,
      });
    

    If you logged branches, you should see the data you are looking for.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search