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, 本教程可能会为您提供帮助。 否则,让我们开始吧。

  • Building the server with Apollo, Node, and GraphQl

    使用Apollo,Node和GraphQl构建服务器

  • GraphQl Schema

    GraphQl模式

  • GraphQl resolvers

    GraphQl解析器

  • Creating the Apollo Server

    创建Apollo服务器

  • Building the Client-side with React

    使用React构建客户端

  • Connecting React to Apollo

    将React连接到Apollo

  • Fetching the data

    取得资料

  • Showing the data

    显示数据

使用Apollo,Node和GraphQl构建服务器 (Building the server with Apollo, Node, and 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模式,以反映我们的数据外观。

GraphQl模式 (GraphQl Schema)

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: IDlogin: Stringavatar_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模式,是时候构建相应的解析器来完成查询操作了。

GraphQl解析器 (GraphQl resolvers)

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服务器。

创建Apollo服务器 (Creating the Apollo Server)

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: IDlogin: Stringavatar_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.

我们开始做吧。

使用React构建客户端 (Building the Client-side with React)

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连接起来。

将React连接到Apollo (Connecting React to Apollo)

  • 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.

如您所见,我们首先导入ApolloClientApolloProvider 。 第一个帮助我们告知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.

也就是说,我们现在可以创建一个显示数据的组件。

取得资料 (Fetching 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 {idloginavatar_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组件接收数据并显示它。

显示数据 (Showing the data)

  • 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 {idloginavatar_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!

谢谢阅读!

翻译自: https://www.freecodecamp.org/news/apollo-graphql-how-to-build-a-full-stack-app-with-react-and-node-js/

react apollo

react apollo_Apollo GraphQL:如何使用React和Node Js构建全栈应用相关推荐

  1. Node.js(MEAN)全栈开发入门-安晓辉-专题视频课程

    Node.js(MEAN)全栈开发入门-28082人已学习 课程介绍         本课程从Node.js切入,以实现一个Web管理系统为目标,以点带面地介绍MEAN技术栈(MongoDB+Expr ...

  2. node.js之全栈开发

    node.js之全栈开发 1.为什么要学习Node.js Node.js是什么 Node能做什么 一些资源 学习到什么 2.Node 2.1起步 安装Node环境 解析执行JavaScript 2.2 ...

  3. Node.js API 全栈 开发框架

    Node.js 框架 Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境. Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效. Node ...

  4. 如何使用Node.js构建完整的GraphQL服务器

    by Jack R. Scott 杰克·R·斯科特(Jack R.Scott) 如何使用Node.js构建完整的GraphQL服务器 (How to build a full GraphQL serv ...

  5. React+Egg.js实现全栈个人博客

    React+Egg.js实现全栈个人博客 这是一个个人博客软件,前台和后台使用的都是React,后端使用egg.js,地址 前台 文章列表 1.png 文章详情 2.png 后台管理系统 添加文章 3 ...

  6. 狼叔直播 Reaction《学习指北:Node.js 2022 全解析》

    大家好,我是若川.持续组织了6个月源码共读活动,感兴趣的可以点此加我微信 ruochuan02 参与,每周大家一起学习200行左右的源码,共同进步.同时极力推荐订阅我写的<学习源码整体架构系列& ...

  7. meetup_如何使用标准库和Node.js构建Meetup Slack机器人

    meetup by Janeth Ledezma 简妮丝·莱德兹玛(Janeth Ledezma) 如何使用标准库和Node.js构建Meetup Slack机器人 (How to build a M ...

  8. 构建node.js基础镜像_我如何使用Node.js构建工作抓取网络应用

    构建node.js基础镜像 by Oyetoke Tobi Emmanuel 由Oyetoke Tobi Emmanuel 我如何使用Node.js构建工作抓取网络应用 (How I built a ...

  9. react-emotion_如何使用Web Speech API和Node.js构建语音转Emotion Converter

    react-emotion Have you ever wondered - can we make Node.js check to see if what we say is positive o ...

最新文章

  1. plsql developer的一些使用
  2. hana::detail::variadic::foldl1用法的测试程序
  3. 教你11 周打造全能Python工程师!
  4. 无线传感器主要应用领域及发展趋势
  5. OpenCV显示中文汉字,未使用CvxText和FreeType库
  6. Qt文档阅读笔记-Qt工作笔记-QThread解析与实例(主线程发送信号给子线程)
  7. linux-用户与组的概念
  8. 计算机系统结构自学试卷,全国2004年4月高等教育自学考试计算机系统结构试题...
  9. java future模式 所线程实现异步调用
  10. c语言 自定义strcmp
  11. 常用算法之-快速排序
  12. BT656跟BT1120和BT709有什么区别
  13. 1483选票统计(一)(结构体专题)
  14. 乐鑫ESP32-S3双核处理器,专为 AIoT 市场打造
  15. kotlin开发Android入门篇八Kotlin开发Android的基本使用
  16. 11,MSI文件简介
  17. 利用粤嵌LinuxGEC6818开发板实现电子相册
  18. python爬取淘宝数据魔方_《淘宝数据魔方技术架构解析》阅读笔记
  19. 侠众道武功最佳练级方案_侠众道二层武功先练什么 武功选择分享
  20. 20221109使用SubtitleEdit-3.6.8-将蓝光DVD中的图形格式的字幕SUP文件通过OCR识别为SRT

热门文章

  1. pptx字体类的相关方法
  2. javascript-内置对象-正则
  3. jquery-ajax-jsonp-360搜索引擎的联想词获取
  4. linux-文件管理-不完整版
  5. SQL Sever sa密码丢失
  6. 生成器案例,#采集日志
  7. element-ui走马灯如何实现图片自适应
  8. Linux的cifs(samba)文件服务
  9. pig:group by之后的其它统计方法一
  10. 学点 C 语言(38): 函数 - 函数指针