I am unable to get the data by using the useQuery in the below mentioned way
const { data:data1 } = useQuery(Get_Doctor);
const { loading, error,data } = useQuery(GET_Branch);
I am unable to get the data by using the useQuery in the below mentioned way
const { data:data1 } = useQuery(Get_Doctor);
const { loading, error,data } = useQuery(GET_Branch);
Indeed you can use multiple queries
const queryMultiple = () => {
const res1 = useQuery(Get_Doctor);
const res2 = useQuery(GET_Branch);
return [res1, res2];
}
const [
{ loading: loading1, data: data1 },
{ loading: loading2, data: data2 }
] = queryMultiple()
What you want to do is compose multiple useQuery into your own custom hook:
But still, its just a syntactic sugar
const { data:doc_data } = useQuery(Get_Doctor);
const { data:branch_data, error: branch_error, loading: branch_loading } = useQuery(GET_Branch);
You just have to rename the data field to have it work. Note that you will have to rename the other
fields like error, loading
etc if any of your queries will be returning them.
IMHO the simple approach is using basic variable object such this way:
const products = useQuery(LIST_PRODUCTS);
const categories = useQuery(LIST_CATEGORY);
//...
if (products.loading) {
console.log("Loading list of products")
} else {
processProducts(products.data)
}
//...
if (categories.loading) {
console.log("Loading list of categories")
} else {
processCategories(categories.data)
}
I think this is simple and more readable.
You can chain them in an if, else-if, and else statement and let the else handle the loading
example:
import React from "react";
import styles from "./home.module.scss";
import { Link } from "react-router-dom";
import { useQuery, gql } from "@apollo/client";
/* query to get home page data */
export const HOME_PAGE_QUERY = gql`
query getHomeData {
home {
title
titleSpan
message
action
}
}
`;
interface PageData {
title: string;
titleSpan: string;
message: string;
action: string;
}
export default function Home() {
const { error, data } = useQuery(HOME_PAGE_QUERY);
// handle error
if (error) return <p>Error :(</p>;
// handle data
else if (data) {
const { home }: { home: PageData } = data;
return (
<article className={styles.home}>
<h1 className={styles["home-title"]}>
{home.title}
<span>{home.titleSpan}</span>
</h1>
<p className={styles["home-message"]}>{home.message}</p>
<Link className={styles["home-action"]} to="/destination">
{home.action}
</Link>
</article>
);
}
// handle loading
else return <p>Loading...</p>;
}
© 2022 - 2024 — McMap. All rights reserved.
; const GET_Branch = gql
{ getBranch(id:"4a045f8c-dad6-4b05-8bd4-3aeb8f7df436") { branchName, address, email } } `; – Reword