MENU
Basic Query
To test the code below, make sure you have the GraphQL server above running ('node server.js') first before launching the React server.
RESETRUNFULL
// RelayEnvironment.jsimport {Environment, Network, RecordSource, Store} from 'relay-runtime';import fetchGraphQL from './fetchGraphQL';async function fetchRelay(params, variables) {
console.log(`fetching query ${params.name} with ${JSON.stringify(variables)}`);
return fetchGraphQL(params.text, variables);}export default new Environment({
network: Network.create(fetchRelay),
store: new Store(new RecordSource()),});
The Relay "Environment" bundles together the configuration, cache storage, and networkhandling that Relay needs to operate.Most applications will use a single Environment instance throughout.
Below, you must use 'AppQuery' as the name of the query, or the compilation will fail.
London
RESETRUNFULL
RESETRUNFULL
// App.jsimport React from 'react';import './App.css';import graphql from 'babel-plugin-relay/macro';import {
RelayEnvironmentProvider,
loadQuery,
usePreloadedQuery,} from 'react-relay/hooks';import RelayEnvironment from './RelayEnvironment';const { Suspense } = React;// Define a query (AppQuery:thisFilename+'Query')const RepositoryNameQuery = graphql`
query AppQuery {
address{
city
}
}`;// Immediately load the query as our app starts. For a real app, we'd move this// into our routing configuration, preloading data as we transition to new routes.const preloadedQuery = loadQuery(RelayEnvironment, RepositoryNameQuery, {
/* query variables */});// Inner component that reads the preloaded query results via `usePreloadedQuery()`.// This works as follows:// - If the query has been completed, it returns the results of the query.// - If the query is still pending, it "suspends" (indicates to React that the//
component isn't ready to render yet). This will show the nearest <Suspense>//
fallback.// - If the query failed, it throws the failure error. For simplicity we aren't//
handling the failure case here.function App(props) {
const data = usePreloadedQuery(RepositoryNameQuery, props.preloadedQuery);
return (
<div className="App">
<header className="App-header">
<p>{data.address.city}</p>
</header>
</div>
);}function AppRoot(props) {
return (
<RelayEnvironmentProvider environment={RelayEnvironment}>
<Suspense fallback={'Loading...'}>
<App preloadedQuery={preloadedQuery} />
</Suspense>
</RelayEnvironmentProvider>
);}export default AppRoot;