react-graphql-example

An example of usage GraphQL and React

Stars
7

Graphql + React simple example

Make query GetExchangeRates here https://48p1r2roz4.sse.codesandbox.io

query GetExchangeRates {
    rates(currency: "USD") {
      currency
      rate
    }
  }

Creat React typescript project

$ npx create-react-app my-app --template typescript
$ yarn add @apollo/client graphql

Connect Apollo Client to React with the ApolloProvider component. src/index.tsx

import {
    ApolloClient,
    InMemoryCache,
    ApolloProvider
} from "@apollo/client";

const client = new ApolloClient({
    uri: 'https://48p1r2roz4.sse.codesandbox.io',
    cache: new InMemoryCache()
});

render(
    <ApolloProvider client={client}>
        <App />
    </ApolloProvider>,
    document.getElementById('root'),
);

Fetch data with useQuery that shares GraphQL data with your UI. src/App.tsx

import React from 'react';
import './App.css';
import {gql, useQuery} from "@apollo/client";

const EXCHANGE_RATES = gql`
  query GetExchangeRates {
    rates(currency: "USD") {
      currency
      rate
    }
  }
`;

function ExchangeRates() {
    const {loading, error, data} = useQuery(EXCHANGE_RATES);

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error :(</p>;

    return data.rates.map(({currency, rate}: { currency: string, rate: number }) => (
        <div key={currency}>
            <p>
                {currency}: {rate}
            </p>
        </div>
    ));
}

function App() {
    return (
        <div>
            <h2>get "Currency Exchange Rates" using Apollo & Graphql</h2>
            <ExchangeRates/>
        </div>
    );
}

export default App;

Official documentation link or https://graphql.org/