react apollo
Apollo Client is a complete state management library for JavaScript apps. It's a powerful tool since it can be used on both the back end and front end side.
Apollo Client是用于JavaScript应用程序的完整状态管理库。 这是一个强大的工具,因为它既可以在后端使用,也可以在前端使用。
In this tutorial, we will use it on the front end and back end by building an Apollo GraphQL Server with Node JS. Then we will consume the data on the client-side using React JS.
在本教程中,我们将通过使用Node JS构建Apollo GraphQL服务器在前端和后端使用它。 然后,我们将使用React JS在客户端使用数据。
If you're new to GraphQl, this tutorial might help you. Otherwise, let's get started.
如果您不熟悉GraphQl, 本教程可能会为您提供帮助。 否则,让我们开始吧。
In this guide, I will use the Github API to have data to show, and that operation will be done by the GraphQl server built with Apollo and Node JS.
在本指南中,我将使用Github API来显示数据,该操作将由使用Apollo和Node JS构建的GraphQl服务器完成。
To make this happen, we need to run the following command on the terminal to set up a new Node JS project:
为此,我们需要在终端上运行以下命令来设置新的Node JS项目:
yarn init
Once the set up is done, we can now install the necessary packages by running this command:
设置完成后,我们现在可以通过运行以下命令来安装必要的软件包:
yarn add apollo-server graphql axios
Great, we now have all we need to build a server. So first let's create a new file app.js
in the root which will be the entry point of our server.
太好了,我们现在拥有构建服务器所需的一切。 因此,首先让我们在根目录中创建一个新文件app.js
,它将是服务器的入口点。
Next, we need to define a Graphql schema that mirrors the way our data should look.
接下来,我们需要定义一个Graphql模式,以反映我们的数据外观。
A schema describes the shape of your data graph. It defines a set of types with fields that are populated from your back-end data stores. So, let's add a new schema in the app.js
file.
模式描述数据图的形状。 它定义了一组类型,这些类型的字段是从后端数据存储中填充的。 因此,让我们在app.js
文件中添加一个新架构。
app.js
app.js
const { ApolloServer, gql } = require("apollo-server")
const axios = require("axios")
const typeDefs = gql`
type User {
id: ID
login: String
avatar_url: String
}
type Query {
users: [User]
}
`
As you can see we don't use all data provided by the Github API. We just need the id that will be used as a reference key on the React App, the login, and the avatar_url. We also have a query users
that returns an array of users.
如您所见,我们并未使用Github API提供的所有数据。 我们只需要将ID用作React App上的参考键,登录名和avatar_url。 我们还有一个查询users
,它返回用户数组。
Now that we have a GraphQL schema, it's time to build the corresponding resolvers to complete the query operation.
现在我们有了GraphQL模式,是时候构建相应的解析器来完成查询操作了。
A resolver is a collection of functions that helps generate a response from a GraphQL query. So, let's add a new resolver in the app.js
file.
解析器是有助于从GraphQL查询生成响应的功能的集合。 因此,让我们在app.js
文件中添加一个新的解析器。
app.js
app.js
const resolvers = {
Query: {
users: async () => {
try {
const users = await axios.get("https://api.github.com/users")
return users.data.map(({ id, login, avatar_url }) => ({
id,
login,
avatar_url,
}))
} catch (error) {
throw error
}
},
},
}
A resolver has to match the appropriate schema by name. Therefore, here users
refers to the users
query defined in our schema. It's a function that fetches the data from the API with the help of axios
and returns as expected the id, the login, and the avatar_url.
解析程序必须按名称匹配适当的架构。 因此,这里的users
指的是在我们的架构中定义的users
查询。 这个函数可以在axios
的帮助下从API提取数据, axios
预期返回ID,登录名和avatar_url。
And that operation can take time to complete. That's why async/await is used here to handle it.
该操作可能需要一些时间才能完成。 这就是为什么在这里使用async / await来处理它的原因。
With that, we can now create the Apollo Server in the next section.
这样,我们现在可以在下一部分中创建Apollo服务器。
If you remember, in the app.js
file, we had imported ApolloServer
from the apollo-server
package. It's a constructor that receives an object as an argument. And that object must contain the schema and the resolver to be able to create the server.
如果您还记得的话,在app.js
文件中,我们已经从apollo-server
包中导入了ApolloServer
。 这是一个接收对象作为参数的构造函数。 并且该对象必须包含架构和解析器,才能创建服务器。
So, let's tweak app.js
a bit with ApolloServer
.
所以,我们修改app.js
一点与ApolloServer
。
app.js
app.js
const server = new ApolloServer({
typeDefs,
resolvers,
})
// typeDefs: typeDefs,
// resolvers: resolvers
server.listen().then(({ url }) => console.log(`Server ready at ${url}`))
Here, we pass as a parameter an object that holds the schema and the resolver to ApolloServer
to create the server and then listens to it. With that in place, we now have a functional server to work with.
在这里,我们将一个持有架构和解析器的对象作为参数传递给ApolloServer
以创建服务器,然后监听它。 有了这个,我们现在可以使用功能服务器。
You can already play with it and send queries with the help of GraphQL playground by running this command:
通过运行以下命令,您已经可以使用它并在GraphQL游乐场的帮助下发送查询:
yarn start
You can now preview it on http://localhost:400
您现在可以在http://localhost:400
上预览它
The complete app.js
file
完整的app.js
文件
const { ApolloServer, gql } = require("apollo-server")
const axios = require("axios")
const typeDefs = gql`
type User {
id: ID
login: String
avatar_url: String
}
type Query {
users: [User]
}
`
const resolvers = {
Query: {
users: async () => {
try {
const users = await axios.get("https://api.github.com/users")
return users.data.map(({ id, login, avatar_url }) => ({
id,
login,
avatar_url,
}))
} catch (error) {
throw error
}
},
},
}
const server = new ApolloServer({
typeDefs,
resolvers,
})
server.listen().then(({ url }) => console.log(`Server ready at ${url}`))
A server alone does not do much. We need to add a start script in the package.json
file to, as you guessed, start the server.
单独一个服务器并不能做很多事情。 如您所料,我们需要在package.json
文件中添加启动脚本,以启动服务器。
package.json
package.json
// first add nodemon: yarn add nodemon --dev
"scripts": {
"start": "nodemon src/index.js"
}
With that, we have a server to fetch data from the Github API. So now it's time to move to the client-side and consume the data.
这样,我们就有了一个服务器,可以从Github API获取数据。 因此,现在是时候移至客户端并使用数据了。
Let's do it.
我们开始做吧。
The first thing we have to do is create a fresh React App by running the following command in the terminal:
我们要做的第一件事是通过在终端中运行以下命令来创建一个新的React App:
npx create-react-app client-react-apollo
Next, we need to install the Apollo and GraphQl packages:
接下来,我们需要安装Apollo和GraphQl软件包:
yarn add apollo-boost @apollo/react-hooks graphql
Now, we can connect Apollo with our React App by updating the index.js
file.
现在,我们可以通过更新index.js
文件将Apollo与我们的React App连接起来。
index.js
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import ApolloClient from 'apollo-boost'
import { ApolloProvider } from '@apollo/react-hooks';
import App from './App';
import './index.css';
import * as serviceWorker from './serviceWorker';
const client = new ApolloClient({
uri: 'https://7sgx4.sse.codesandbox.io'
})
ReactDOM.render(
<React.StrictMode>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
As you can see, we start by importing ApolloClient
and ApolloProvider
. The first helps us inform Apollo about which URL to use when fetching data. And if no uri
is passed to ApolloClient
, it will take the current domain name plus /graphql
.
如您所见,我们首先导入ApolloClient
和ApolloProvider
。 第一个帮助我们告知Apollo在获取数据时要使用哪个URL。 如果没有uri
传递给ApolloClient
,它将使用当前域名加上/graphql
。
The second is the Provider which expects to receive the client object to be able to connect Apollo to React.
第二个是希望接收客户端对象以能够将Apollo连接到React的Provider。
That said, we can now create a component that shows the data.
也就是说,我们现在可以创建一个显示数据的组件。
App.js
App.js
import React from "react"
import { useQuery } from "@apollo/react-hooks"
import gql from "graphql-tag"
import "./App.css"
const GET_USERS = gql`
{
users {
id
login
avatar_url
}
}
`
Here, we have a simple GraphQL query that fetches the data. That query will be passed later to useQuery
to tell Apollo which data to fetch.
在这里,我们有一个简单的GraphQL查询来获取数据。 该查询将稍后传递给useQuery
以告知Apollo要提取哪些数据。
App.js
App.js
const User = ({ user: { login, avatar_url } }) => (
<div className="Card">
<div>
<img alt="avatar" className="Card--avatar" src={avatar_url} />
<h1 className="Card--name">{login}</h1>
</div>
<a href={`https://github.com/${login}`} className="Card--link">
See profile
</a>
</div>
)
This presentational component will be used to display a user. It receives the data from the App component and displays it.
此演示组件将用于显示用户。 它从App组件接收数据并显示它。
App.js
App.js
function App() {
const { loading, error, data } = useQuery(GET_USERS)
if (error) return <h1>Something went wrong!</h1>
if (loading) return <h1>Loading...</h1>
return (
<main className="App">
<h1>Github | Users</h1>
{data.users.map(user => (
<User key={user.id} user={user} />
))}
</main>
)
}
export default App
The useQuery
hook provided by Apollo receives the GraphQL query and returns three states: the loading, the error, and the data.
Apollo提供的useQuery
挂钩接收GraphQL查询并返回三种状态:加载,错误和数据。
If the data are successfully fetched, we pass it to the User component. Otherwise we throw an error.
如果成功获取了数据,我们会将其传递给用户组件。 否则,我们将引发错误。
The complete App.js
file
完整的App.js
文件
import React from "react"
import { useQuery } from "@apollo/react-hooks"
import gql from "graphql-tag"
import "./App.css"
const GET_USERS = gql`
{
users {
id
login
avatar_url
}
}
`
const User = ({ user: { login, avatar_url } }) => (
<div className="Card">
<div>
<img alt="avatar" className="Card--avatar" src={avatar_url} />
<h1 className="Card--name">{login}</h1>
</div>
<a href={`https://github.com/${login}`} className="Card--link">
See profile
</a>
</div>
)
function App() {
const { loading, error, data } = useQuery(GET_USERS)
if (error) return <h1>Something went wrong!</h1>
if (loading) return <h1>Loading...</h1>
return (
<main className="App">
<h1>Github | Users</h1>
{data.users.map(user => (
<User key={user.id} user={user} />
))}
</main>
)
}
export default App
Great! With that, we are now done building a full-stack Apollo GraphQL app using React and Node JS.
大! 至此,我们现在已经完成了使用React和Node JS构建全栈Apollo GraphQL应用程序的过程。
Preview the Apollo GraphQL Server here
在此处预览Apollo GraphQL服务器
Preview the React App here
在此处预览React App
Find the source code here
在这里找到源代码
You can find other great content like this on my blog
您可以在我的博客中找到类似的其他精彩内容
Thanks for reading!
谢谢阅读!
react apollo