After the basic introduction of the previous chapter, you have a basic understanding of GraphQL, and you can also build a simple GraphQL Server. How to connect to graphQL Server and request data in react front-end project?
What is Relay?
Relay provides a solution for requesting and managing graphQL data in the React application. It is a framework based on GraphQL and React, which combines the two components to further encapsulate requests into components based on the original React component.
Here is a step-by-step guide to using Relay in react projects.
Basic building
Create a React project using create-react-app
npx create-react-app relay-test
yarn add --dev customize-cra react-app-rewired
Copy the code
Build Relay
Install the react – relay
yarn add react-relay
Copy the code
Install babel-plugin-relay and configure. Babelrc
Relay needs to run before other Babel plug-ins or Babel Preset to ensure that the GRAPHQL syntax is translated correctly
yarn add --dev babel-plugin-relay graphql
// .babelrc
{
"plugins": [["relay", {
"schema": "schema.graphql"."artifactDirectory": "./src/__generated__"}}]]Copy the code
Install relay to parse the relay-compiler and add the relay script to package.json
After YARN relay, the __generated__ directory is automatically generated in the SRC directory
yarn add --dev relay-compiler
// package.json
"scripts": {
"relay": "relay-compiler --src ./src --schema ./schema.graphql --artifactDirectory ./src/__generated__"."start": "yarn relay && react-app-rewired start"
}
Copy the code
Create a file config-overrides. Js in the root directory to override the webPack configuration.
Note: In devServer configuration, we proxy/graphQL request to http://localhost:4000/, which is the GraphQL server we built in Section 1, and then we can get data through/graphQL request.
const {
override,
addBabelPlugins,
addWebpackAlias,
addDecoratorsLegacy,
fixBabelImports,
disableEsLint
} = require('customize-cra');
const path = require('path');
module.exports = {
webpack: override(
// Add Babel relay. addBabelPlugins(['relay', { artifactDirectory: './src/__generated__' }]),
/ / add alias
addWebpackAlias({
'src': path.resolve(__dirname, 'src')}),// Install antd and babel-plugin-import before using antd
fixBabelImports('import', {
libraryName: 'antd'.libraryDirectory: 'es'.style: 'css'
})
),
devServer (configFunction) {
return (proxy, allowedHost) = > {
const config = configFunction({
'/graphql': {
target: 'http://localhost:4000/'.changeOrigin: true
}
}, allowedHost)
return config
}
}
}
Copy the code
The business scenario
Based on the user list data of GraqHQL Server, we first try to use GraphQL to request user list Users, and display a table of users in the front end. The directory structure is as follows
schema
Schema.graphql is created in the root directory to define the query and mutation available to the client.
Note: This is consistent with the server schema
type Query {
users: [User]! user (id: ID!) : User! } type Mutation { addUser (id: ID! , name:String! , email:String! , age: Int): User updateUser (id: ID! , name:String.email: String.age: Int): User deleteUser(id: ID!) : User! } type User {id: ID!
key: Int!
name: String!
email: String!
age: Int!
}
Copy the code
QueryRenderer
The Relay framework provides a high-level component (HOC) called the QueryRenderer to encapsulate the React component and the GraphQL request. This component accepts four Props: Environment, Query, Variables, and Render. Environment needs to be configured with network request and Store. Query accepts the GraphQL request; The variables accept the variables required in the GraphQL request, and the final render is used to define the rendering of the component. Citation >>
Note: In relay, the Operation name defined by the component must start with a filename and end with Query or Mutation. For example, the Operation name of a query defined in SRC/approute.js is AppRouteQuery.
// src/AppRoute.js
import React from 'react';
import { graphql, QueryRenderer } from 'react-relay';
import Home from './pages/home';
import environment from './lib/environment';
const AuthRoute = () = > {
return <QueryRenderer
environment={environment}
query={graphql`
query AppRouteQuery {
users {
key
name
age
email`}}}render={({error, props}) = > {
if (props) {
return <Home data={props.users}/>
}
}}
/>
}
export default AuthRoute;
Copy the code
Environment is used to configure network requests and stores. The Store here is the RecordStore. Relay records an ID for each requesting node, which is stored as a record in the store.
// src/lib/environment.js
import {
Environment,
Network,
RecordSource,
Store
} from 'relay-runtime';
const modernEnvironment = new Environment({
network: Network.create(async (operation, variables) => {
const response = await fetch('/graphql', {
method: 'POST'.headers: {
'Content-Type': 'application/json',},body: JSON.stringify({
query: operation.text,
variables,
})
})
return response.json();
}),
store: new Store(new RecordSource())
})
export default modernEnvironment;
Copy the code
Home Table rendering interface, using ANTD Table component rendering.
// src/pages/home/index
import {Table} from 'antd';
export default function Home (props) {
const columns = [{
title: 'name'.dataIndex: 'name'.key: 'name'
}, {
title: 'age'.dataIndex: 'age'.key: 'age'
}, {
title: 'email'.dataIndex: 'email'.key: 'email'
}]
return <Table dataSource={props.data} columns={columns} />;
}
Copy the code
Project start
After yarn start, the relay in SRC is parsed to generate the SRC /__generated__ directory containing the parsed.graphql.js file. Then the client service is started, localhost:3000 is opened, and localhost:3000 is opened. You can see that the user list has been requested and rendered.
At this point, you’re done!
The last
Fragment and Mutation relay usage, not demonstrated one by one. Interested in children’s boots can continue to research.
Relay document