This starter contains everything needed to start a full-featured React application, powered by GraphQL.
It uses graphql-code-generator
to generate a file (default located to src/graphql/components.tsx
) which contains definitions for all *.graphql files in graphql
folder.
Use
$ yarn dev
to launch concurrently the create-react-app default start script and gql-code-gen, which runs a watcher that re-update files definitions.
All configuration related files are located in the codegen.yml
file (more informations here)
Example usage for a given query
query ProjectsQuery {
projects {
edges {
node {
title
id
body
languages {
name
}
createdAt
categories {
name
slug
}
}
}
}
}
which generate a hook and a component and could be used like this :
import React, { FC } from "react"
import { useProjectsQuery } from "/src/graphql/components" // This file is generated by gql-code-gen
const Projects: FC = () => {
const { data, loading, error } = useProjectsQuery()
if (error) {
return <div>Error</div>
}
if (loading) {
return <div>Loading...</div>
}
if (data) {
// ...
}
return null;
}
const App: FC = () => {
return (
<div className="App">
<main>
<Projects/>
</main>
</div>
);
}
export default App
If you are not using React Hooks, you could use it like this
import React, { Suspense, FC }from "react"
import { ProjectsQueryComponent } from "/src/graphql/components" // This file is generated by gql-code-gen
const App: FC = () => {
return (
<div className="App">
<header className="App-header">
<h1>Header</h1>
</header>
<main>
<ProjectsQueryComponent>
{({ data, error, loading }) => {
if (error) { return <div>Error... </div> }
if (loading) { return <div>Loading... </div> }
if (data) { return <ul>
{data.projects!.edges!.map(edge => edge!.node).map(project =>
<li key={project.id}>{project.title}</li>
)}
</ul>}
return null
}}
</ProjectsQueryComponent>
</main>
</div>
);
}
export default App
and you get all the nice autocompletion from your IDE thanks to Typescript! And if you change your *.graphql file to add a new field for a GraphQL query, it will be automatically generated and you will be always in sync with your GraphQL files!