Your GraphQL Hook
Using the Hook
The hook you build using the hook builder allows you to perform a GraphQL request from within a react component.
It takes an optional config object and returns a tuple with 3 elements:
- A state object containing information about the request and possibly the results or errors
- A submit function if you want to run the request manually
- An abort function if you want to abort the request manually (it will be aborted automatically when the component gets unmounted).
All of this completely type-safe!
Example
import { graphQL } from "@react-nano/use-graphql";
// See the examples in the "Hook Builder" section.
const useUserQuery = graphQL.query("user")...;
export function UserSummary({ id }: UserSummaryProps) {
const [userState] = useUserQuery({ url: "/graphql", autoSubmit: { id } });
if (!userState.success) return <div>Loading</div>;
const user = userState.data;
return (
<ul>
<li>Name: {user.name}</li>
<li>Icon: <img src={user.icon} alt="User Icon" /></li>
<li>Posts:
<ul>
{user.posts.map((post) => (
<li key={post.id}>{post.title} with {post.hits} hits</li>
))}
</ul>
</li>
</ul>
);
}
The State Object
The state object always has these properties:
loading: boolean
=> Request is currently in progressfailed: boolean;
=> Either an exception occurred or the request returned an errorsuccess: boolean;
=> Request was successfultype: "empty" | "success" | "error" | "exception"
=> The last known state of the request (a new request might be in progress)
Depending on type
, additional properties might be available:
"empty"
=> This is the initial state if no request has returned yetfailed
will always befalse
success
will always befalse
"success
=> This is the state when a request returned successful.failed
will always befalse
success
will always betrue
responseStatus: number;
=> The status code of the responseresponseHeaders: Headers;
=> The headers of the responsedata: ResultType
=> The server result
"error"
=> The server responded with an error.failed
will always betrue
success
will always befalse
responseStatus: number;
=> The status code of the responseresponseHeaders: Headers;
=> The headers of the responseerrors: ErrorType[];
=> The list of errors returned by the server
"exception"
=> An exception has been thrown in JavaScriptfailed
will always betrue
success
will always befalse
errors: Error;
=> The error that has been thrown
The Submit Function
The submit function arguments depend on wether you defined variables in your hook:
- If you defined variables, you'll need to pass them as an object to the submit function.
- E.g.
submit({ id: "hello" });
- E.g.
- Otherwise, call the submit function without arguments.
The Abort Function
This function is simple. It takes no arguments and stops the request.