How to implement GraphQL in a React app?
- 2019-04-07 07:43 AM
Let's use React Apollo. This lib will allow you to fetch data from GraphQL server and use it the React framework.
Before you start make sure that you have Node.js installed. To get started we first need to set up a new React project. The easiest way to do so is to use create-react-app, which allows you to create a new React project with zero build configuration.
Once you have above done the next step will be to install dependencies. You can do it with a single NPM command which will install the following packages:
apollo-boost: a package with all necessary Apollo Client components
react-apollo: a view layer for React
graphql-tag: both required to parse GraphQL queries
Now you need to create an instance of Apollo Client. You can do it
App.js by adding the following code:
To start with, all you really need is the endpoint for your GraphQL server. Let’s assume you already have your GraphQL schema created (you can see how to do it quickly here). You can define it in
uri or it will be
/graphql endpoint on the same host as your app by default.
To connect the Apollo Client to React use the
ApolloProvider component exported from
ApolloProvider works similar to React’s context provider:
- it wraps your React app,
- places the client on the context,
giving you access to it anywhere in your component tree.
Your first React app with GraphQL is up and running you can start fetching some data with GraphlQL Queries!
Thanks for reading ❤
☞ The Modern GraphQL Bootcamp (Advanced Node.js)
☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)
☞ GraphQL with React: The Complete Developers Guide
☞ React - The Complete Guide (incl Hooks, React Router, Redux)
☞ Modern React with Redux [2019 Update]
☞ Build a Health Tracking App with React, GraphQL, and User Authentication
☞ GraphQL API with AWS and Use with React
☞ How to build GraphQL APIs with Kotlin, Spring Boot, and MongoDB?
☞ Build a Simple Web App with Express, Angular, and GraphQL
Originally published by Tomek Poniatowicz at https://dev.to