Update React example to use AC3 and hooks

This commit is contained in:
Trevor Blades
2020-01-31 14:27:55 -08:00
committed by GitHub
parent 76427f7f9d
commit 44211746b9

View File

@@ -10,25 +10,24 @@ This example uses [React](https://reactjs.org/) and [Apollo GraphQL](https://apo
## Install dependencies
```shell
$ npm install react react-dom react-apollo apollo-boost graphql graphql-tag
$ npm install react react-dom @apollo/client graphql
```
## Build the component
```js
import ApolloClient from 'apollo-boost';
import React, {Component} from 'react';
import React, {useState} from 'react';
import ReactDOM from 'react-dom';
import gql from 'graphql-tag';
import {Query} from 'react-apollo';
import {ApolloClient, InMemoryCache, gql, useQuery} from '@apollo/client';
// initialize a GraphQL client
const client = new ApolloClient({
cache: new InMemoryCache(),
uri: 'https://countries.trevorblades.com'
});
// write a GraphQL query that asks for names and codes for all countries
const GET_COUNTRIES = gql`
const LIST_COUNTRIES = gql`
{
countries {
name
@@ -37,36 +36,24 @@ const GET_COUNTRIES = gql`
}
`;
// create a component that renders an API data-powered select input
class CountrySelect extends Component {
state = {
country: 'US'
};
// create a component that renders a select input for coutries
function CountrySelect() {
const [country, setCountry] = useState('US');
const {data, loading, error} = useQuery(LIST_COUNTRIES, {client});
// set the selected country to the new input value
onCountryChange = event => {
this.setState({country: event.target.value});
};
render() {
return (
<Query query={GET_COUNTRIES} client={client}>
{({loading, error, data}) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>{error.message}</p>;
return (
<select value={this.state.country} onChange={this.onCountryChange}>
{data.countries.map(country => (
<option key={country.code} value={country.code}>
{country.name}
</option>
))}
</select>
);
}}
</Query>
);
if (loading || error) {
return <p>{error ? error.message : 'Loading...'}</p>;
}
return (
<select value={country} onChange={event => setCountry(event.target.value)}>
{data.countries.map(country => (
<option key={country.code} value={country.code}>
{country.name}
</option>
))}
</select>
);
}
ReactDOM.render(<CountrySelect />, document.getElementById('root'));