First create a new React application using React Create App:
npx create-react-app my-app
Then enter inside the my-app
directory, install the graphql-hooks
package, and start the development server:
cd my-appyarn add graphql-hooksyarn start
First you'll need to create a GraphQL client pointing to one of the GraphQL Content Delivery API endpoints and wrap your app with the provider:
// src/index.jsimport React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import * as serviceWorker from './serviceWorker';import { GraphQLClient, ClientContext } from 'graphql-hooks'const client = new GraphQLClient({url: "https://graphql.datocms.com/",headers: {"Authorization": "Bearer YOUR_API_TOKEN",}});ReactDOM.render(<React.StrictMode><ClientContext.Provider value={client}><App /></ClientContext.Provider></React.StrictMode>,document.getElementById("root"));serviceWorker.unregister();
Make sure you replace YOUR_API_TOKEN
with an actual API token of your DatoCMS project. You can create a new one under "Settings > API Tokens".
Next, go to src/App.js
and use the useQuery
hook to perform your GrapQL query:
import React from "react";import { useQuery } from "graphql-hooks";import "./App.css";const HOMEPAGE_QUERY = `query HomePage($limit: IntType) {allBlogPosts(first: $limit) {title}}`;function App() {const { loading, error, data } = useQuery(HOMEPAGE_QUERY, {variables: {limit: 10}});if (loading) return "Loading...";if (error) return "Something Bad Happened";return (<div className="App">{JSON.stringify(data)}</div>);}export default App;
The HOMEPAGE_QUERY
is the GraphQL query, and of course it depends on the models available in your define in your specific DatoCMS project.
You can learn everything you need regarding how to build GraphQL queries on our Content Delivery API documentation.