英文:
can i use graphql in react without using Apollo?
问题
我正在尝试在React中使用GraphQL。建议使用Apollo Client来实现应用程序中的GraphQL,但我一开始不想使用它。是否可以在不使用Apollo Client的情况下将GraphQL用于React?
英文:
i am trying to use the GraphQl with react.
suggestions gives that to use apollo client for react to implement the graphql to the application.
but i don't want to use it in the first place.
can i use graphql to react without using apollo client?
答案1
得分: 20
是的,我们可以在不使用Apollo Client的情况下在React中使用GraphQL。我们可以使用fetch或axios,并使事情正常运作。
下面的示例演示了使用fetch来查询GraphQL端点的用法。
fetch(<graphql_endpoint>, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: '{ posts { title } }' }),
})
.then(res => res.json())
.then(res => console.log(res.data));
使用axios也可以轻松实现相同的效果。希望这对你有所帮助!
英文:
Yes. We can use GraphQL with React without using Apollo Client. We can use fetch or axios and can make things work the same.
Below example demonstrates the usage of fetch to query a GraphQL endpoint.
fetch(<graphql_endpoint>, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: '{ posts { title } }' }),
})
.then(res => res.json())
.then(res => console.log(res.data));
Same thing can be easily achieved using axios. Hope this helps!
答案2
得分: 8
是的,因为GraphQL是一个规范,而不仅仅是一家公司的实现(无论人们如何认为该实现的质量有多好)。在其核心,GraphQL只是一种查询格式和结构化响应。甚至网络调用也不是绝对必要的。
在浏览器中,你也可以跳过Apollo,只需发起一个普通的网络请求。你可以使用XMLHttpRequest或Fetch API轻松进行GraphQL查询的AJAX调用。我认为最简单的方法是安装GraphiQL或Playground,然后在浏览器的开发工具中执行查询。大多数浏览器开发工具的网络选项卡将显示你所需的所有请求标头和URL参数。
Apollo客户端只是为你完成了很多工作,并有一个非常健康的生态系统,可以添加缓存、联合等功能,但没有任何阻止你跳过该库并自己进行HTTP调用的中间人。
英文:
Yes, because GraphQL is a spec rather than just one company's implementation (no matter how good many consider that implementation to be). At its core, GraphQL is just a query format and structured response. Even a network call is not strictly needed.
You could skip Apollo in the browser too, and just invoke a plain web request. You can easily make an AJAX call with XMLHttpRequest or Fetch API to perform the GraphQL query. The easiest way I can think of to work this out is to install GraphiQL or Playground somewhere, open up your browser's developer tools, and execute a query. The Network tab of most browser's developer tools will show you all of the request headers and URL parameters you would need.
The Apollo client just does a lot of that work for you and has a very healthy ecosystem to add caching, federation, etc., but there is nothing stopping you from skipping that library and making the HTTP calls yourself with no middlemen.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论