Created
March 13, 2023 17:56
-
-
Save horne3754sg/548d66538ef8fd8e68d396b892d7c6fd to your computer and use it in GitHub Desktop.
Basic React Router v6 and Relay integration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This may not be the most ideal way, but it works for me. | |
* | |
* You have to use one of their data routers in order to support loaders. https://reactrouter.com/en/main/routers/picking-a-router | |
* | |
* Then you can use loaders https://reactrouter.com/en/main/route/loader | |
* | |
* I played around with it for a while and eventually came up with something like this. | |
*/ | |
// Add a route to you data router. | |
<Route path="users" element={<Users />} loader={usersLoader} /> | |
// Create your route component and define your query, loader and Page component | |
const query = graphql` | |
query UserQuery { | |
viewer { | |
...SomeListComponentFragment | |
} | |
} | |
`; | |
export const usersLoader = () => { | |
return routeDataLoader<UserQuery>(query, {}, { fetchPolicy: "store-and-network" }); | |
}; | |
export default function UsersPage() { | |
const { data } = usePreloadedLoaderData<UserQuery>(query); | |
return <SomeListComponent user={data?.viewer} /> | |
} | |
// Utility hooks in order to simplify the process and add types, it could be better? | |
export const routeDataLoader: <TQuery extends OperationType>( | |
preloadableRequest: GraphQLTaggedNode | PreloadableConcreteRequest<TQuery>, | |
variables?: VariablesOf<TQuery>, | |
options?: LoadQueryOptions | |
) => PreloadedQuery<TQuery> = (preloadableRequest, variables, options) => { | |
return loadQuery(environment, preloadableRequest, variables || {}, options); | |
}; | |
export const usePreloadedLoaderData: <TQuery extends OperationType>( | |
gqlQuery: GraphQLTaggedNode | |
) => PreloadedQuery<TQuery> & { | |
data: TQuery["response"]; | |
} = <TQuery extends OperationType>(gqlQuery: GraphQLTaggedNode) => { | |
const preloadedQueryRef = useLoaderData() as PreloadedQuery<TQuery>; | |
return { | |
...preloadedQueryRef, | |
data: usePreloadedQuery(gqlQuery, preloadedQueryRef), | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment