Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can i use graphql in react without using Apollo?

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?

like image 814
FEDev Avatar asked Jan 06 '20 18:01

FEDev


2 Answers

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!

like image 165
Kirankumar Ambati Avatar answered Oct 17 '22 01:10

Kirankumar Ambati


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.

like image 36
Miles Elam Avatar answered Oct 17 '22 01:10

Miles Elam